简体   繁体   English

如何在Swift 2中解析JSON?

[英]How to parse JSON in Swift 2?

I have a PHP web api that returns json in the following format: 我有一个PHP Web API,它以以下格式返回json:

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

]}

In my Swift 2 code, I am able to retrieve the data above store it in an NSArray named users 在我的Swift 2代码中,我能够检索以上数据并将其存储在名为usersNSArray

Now, I need to iterate throw each user to convert it into an object: 现在,我需要迭代抛出每个user以将其转换为对象:

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

That ouputs something like: 输出类似:

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

but when I try to access any element of that object I get an error: 但是当我尝试访问该对象的任何元素时,我得到一个错误:

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

在此处输入图片说明 Then I tried : 然后我尝试了:

if let u=user["user"] {     //does not work: Xcode wont compile
    // do somthing
}

I put a break point at print("\\(user)") to see what is going on, and here is what I found: 我在print("\\(user)")处设置了一个断点,以查看发生了什么,这是我发现的结果:

在此处输入图片说明

When I print the description of each individual user I get: 当我打印每个user的描述时,我得到: 在此处输入图片说明

How can I access the elements of this JSON data in Swift 2? 如何在Swift 2中访问此JSON数据的元素?

A NSArray only holds AnyObject so you have to cast it (to Array<Dictionary<String, Dictionary<String, String>>> . Below you see the shorthand): 一个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