swift json type data parsing after get data -
i'm developing function receiving json after calling nsurlrequest
in swift. having issues accessing different data values subscript after have parsed result.
the following retrieved json:
{"retcode":100,"retmsg":"success","retdata":{"usn":92,"id":"clipsys@gmail.com","nickname":"ppigimi","profile_image":"..\/upload\/profile\/20150528172839.jpeg","language":"jp","join_channel_nm":"korfolk","cert_key":"696d6fb453dc141e5295e9d8e37b8dd0f1afc8e34ce30b74551ed74a447ac564","cert_flag":"y","join_date":"20150518155650","token":"3ea0a5fec1b55a5a23b5f1dc5c14b040dcd71eea"}}
the following code. don't know how values usn
, token
inside of retdata
.
let task = nsurlsession.sharedsession().datataskwithrequest(request) { data, response, error in if error != nil { println("error=\(error)") return } // can print out response object println("response = \(response)") // print out response body let responsestring = nsstring(data: data, encoding: nsutf8stringencoding) println("responsestring = \(responsestring)") //let's convert response sent server side script nsdictionary object: var err: nserror? var myjson = nsjsonserialization.jsonobjectwithdata(data, options: .mutableleaves, error:&err) as? nsdictionary if let parsejson = myjson as? [string: anyobject] { // can access value of first name key var retcode = parsejson["retcode"] as? int println("retcode: \(retcode)") if let retdata = parsejson["retdata"] as? [anyobject] { data in retdata { /**let usn = data["usn"] println("usn = \(usn)")**/ } } if retcode == 100 { //nsuserdefaults.standarduserdefaults().setvalue("usn", forkey: string) } dispatch_async(dispatch_get_main_queue(), { var myalert = uialertcontroller(title: "alert", message: "aaaaaa", preferredstyle: uialertcontrollerstyle.alert); let okaction = uialertaction(title: "ok", style:uialertactionstyle.default) { action in self.dismissviewcontrolleranimated(true, completion: nil); } myalert.addaction(okaction); self.presentviewcontroller(myalert, animated: true, completion: nil); }); } } task.resume()
the problem accessing retcode
[anyobject]
. not array
, json object. need cast dictionay
, example [string : anyobject]
.
this means for
loop accessing data can following:
if let retdata = parsejson["retdata"] as? [string : anyobject] { data in retdata { println("data is: \(data)") /**let usn = data["usn"] println("usn = \(usn)")**/ } }
Comments
Post a Comment