这是我从服务器收到的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 :(得分: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本机类型时,无需使用(反)序列化指定选项。