繁体   English   中英

如何在Swift 2中解析JSON?

[英]How to parse JSON in Swift 2?

我有一个PHP Web API,它以以下格式返回json:

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

]}

在我的Swift 2代码中,我能够检索以上数据并将其存储在名为usersNSArray

现在,我需要迭代抛出每个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数据的元素?

一个NSArray只保存AnyObject因此您必须将其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)")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM