如何在 Swift 2 中解析 JSON?
How to parse JSON in Swift 2?
我有一个 PHP 网络 api returns json,格式如下:
{"users":[
{"user": {id:"1","name":"ahmad"}},
...
]}
在我的 Swift 2 代码中,我能够检索上面的数据并将其存储在名为 users
的 NSArray
中
现在,我需要迭代抛出每个 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 数据的元素?
A NSArray
只包含 AnyObject
所以你必须将它转换为 Array<Dictionary<String, Dictionary<String, String>>>
。下面你会看到 shorthand:
// 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)")
}
我有一个 PHP 网络 api returns json,格式如下:
{"users":[
{"user": {id:"1","name":"ahmad"}},
...
]}
在我的 Swift 2 代码中,我能够检索上面的数据并将其存储在名为 users
NSArray
中
现在,我需要迭代抛出每个 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 数据的元素?
A NSArray
只包含 AnyObject
所以你必须将它转换为 Array<Dictionary<String, Dictionary<String, String>>>
。下面你会看到 shorthand:
// 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)")
}