Response:
{
"access_token" = 91BB0E206CC453B75349F185876F0D80;
nickname = Hari;
"open_id" = 4889ACDAA79490B10E4F196876144181;
province = "";
}
I need to get the access_token,nickname from the above response.
MyCode in Swiftenter code here
let jsonObjects=object as! NSArray
for dataDict : Any in jsonObjects
{
let access_token: NSString! = (dataDict as AnyObject).object(forKey: "access_token") as! NSString
let nickname: NSString! = (dataDict as AnyObject).object(forKey: "nickname") as! NSString
print (access_token!)
print (nickname!)
}
Error:
Could not cast value of type '__NSDictionaryM' (0x114a120e0) to 'NSArray' (0x114a11c58).
In order to avoid such crashes, a better way to access json data is the following:
if let json = jsonData as? [String: Any] {
if let token = json["access_token"] as? String {
self.accesToken = token
}
if let nickname = json["nickname"] as? String {
self.nickname = nickname
}
}
You can cast each of the objects to the type you expect them to be, if they are not, nothing happens. If you need something to happen, you can and an else
to each of the checks.