I'm developing a function which is receiving some JSON after calling a NSURLRequest
in Swift. I am having issues accessing the different data values with subscript after I have parsed the result.
The following is the retrieved JSON:
{"retCode":100,"retMsg":"Success","retData":{"usn":92,"id":"[email protected]","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 is my code. I don't know how to get the values usn
and token
inside of retData
.
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
return
}
// You 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 from a server side script to a NSDictionary object:
var err: NSError?
var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary
if let parseJSON = myJSON as? [String: AnyObject] {
// Now we can access value of First Name by its key
var retCode = parseJSON["retCode"] as? Int
println("retCode: \(retCode)")
if let retData = parseJSON["retData"] as? [AnyObject] {
for 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 is that you are accessing
retCode
as[AnyObject]
. It is not anArray
, but actually a JSON object. You will need to cast it to aDictionay
, for example[String : AnyObject]
.This means that your
for
loop where you are accessing the data can look something like the following: