簡體   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