2017-02-02 41 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欢迎伴侣:) –