[英]How to parse JSON in Swift 2?
我有一個PHP Web API,它以以下格式返回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數據的元素?
一個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.