2017-02-02 40 views
-3

這是我從服務器收到的JSON響應。我試圖解析值沒有任何成功。如何解析Swift 3中這個JSON響應的值?

{"items": 
    [{"item": 
    { "id":824, 
     "company_id":31, 
     "config_id":45, 
     "imagesmall":null, 
     "imagethumb":null, 
     "pointofsales":null, 
     "status":true, 
     "endPlanned":false 
     } 
    }, 
    {"item": 
    { "id":889, 
     "company_id":74, 
     . 
     . 
     . 
     "status":true, 
     "endPlanned":false 
    } 
    }] 
} 

代碼我想

if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{ 
    print(json) // does work 
    let item = json?["items"] as? [[String: Any]] 
    print(item?[0]) // does work 
    // ... from here I am looking for the code to access the values and print it out ... 
} 
+0

告訴我們你試過的東西。 –

+1

不在這裏[編輯您的問題](http://stackoverflow.com/posts/42000176/edit)與您的嘗試代碼和什麼不工作。 –

回答

0

要打印item您通過items陣列需要循環。

if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any], 
    let items = json["items"] as? [[Strin:Any]] { 

    for item in items { 
     if let dic = item["item"] as? [String:Any] { 
      print(dic["id"]) 
      print(dic["company_id"]) 
      print(dic["config_id"]) 
      //and so on.. 
     } 
    } 
} 

注:與SWIFT自身的類型也沒有必要指定用(反)序列化的選項。

+0

非常感謝!看起來很容易....我剛剛開始嘗試用我自己的方式克服這些問題,但有時我只是卡住了:-) – Jim

+0

@Jim歡迎伴侶:) –