我有一个PHP Web API,它以以下格式返回json:
{"users":[
{"user": {id:"1","name":"ahmad"}},
...
]}
在我的Swift 2代码中,我能够检索上面的数据并将其存储在一个NSArray
命名为users
现在,我需要迭代抛出每个user
将其转换为对象:
for user in users {
print("found: \(user)")
}
输出类似:
found: {
user = {
id = 1;
name = ahmad;
};
}
但是当我尝试访问该对象的任何元素时,我得到一个错误:
let id = user["user"]["id"] //does not work: Xcode wont compile
let id2 = user["user"]!["id"]! //does not work: Xcode wont compile
let id3 = user!["user"]!["id"]! //does not work: Xcode wont compile
然后我尝试了:
if let u=user["user"] { //does not work: Xcode wont compile
// do somthing
}
我在print("\(user)")
此处设置了一个断点,以查看发生了什么,这就是我发现的结果:
当我打印每个人的描述时,user
我得到:
如何在Swift 2中访问此JSON数据的元素?
ANSArray
仅保留,AnyObject
因此您必须将其强制转换(到Array<Dictionary<String, Dictionary<String, String>>>
。在下面,您可以看到速记):
// this is a forced cast and you probably get runtime errors if users cannot be casted
for user in users as! [[String : [String : String]]] {
print("found: \(user)")
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句