响应:
{
"access_token" = 91BB0E206CC453B75349F185876F0D80;
nickname = Hari;
"open_id" = 4889ACDAA79490B10E4F196876144181;
province = "";
}
我需要从上面的回复中获取access_token,昵称。
这里的Swiftenter代码中的MyCode
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!)
}
错误:
Could not cast value of type '__NSDictionaryM' (0x114a120e0) to 'NSArray' (0x114a11c58).
答案 0 :(得分:0)
为了避免此类崩溃,访问json数据的更好方法如下:
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
}
}
您可以将每个对象转换为您期望的类型,如果不是,则不会发生任何事情。如果您需要某些事情发生,您可以和else
进行每项检查。