如何在Swift 2中解析JSON?

时间:2015-07-06 10:35:26

标签: json swift2

我有一个PHP web api,它以下列格式返回json:

{"users":[
   {"user": {id:"1","name":"ahmad"}},
   ...

]}

在我的Swift 2代码中,我能够检索上面的数据,将其存储在名为NSArray的{​​{1}}

现在,我需要迭代抛出每个users以将其转换为对象:

user

输出类似的东西:

for user in users {
    print("found: \(user)")
}

但是当我尝试访问该对象的任何元素时,我收到错误:

found: {
    user =     {
        id = 1;
        name = ahmad;
    };
}

enter image description here 然后我试了一下:

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 } 处设置了一个断点,看看发生了什么,这就是我发现的:

enter image description here

当我打印每个人print("\(user)")的描述时,我得到: enter image description here

如何在Swift 2中访问此JSON数据的元素?

1 个答案:

答案 0 :(得分:2)

NSArray只保留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)")
}