我试图从调用Web服务的结果中填充UITableView。数据以JSON格式返回,如下所示
[{"name":"CONTROL TEST",
"nc_lead":"TOM SMITH",
"datastr":"N/A",
"username":"tsmith",
"status":"REOPENED",
"orderno":"00000000",
"ccsText":"000",
"risk":0,
"dateTimeCreated":"2016-01-29 13:16:50",
"supplyStart":"2016-02-08T11:51:00+0000",
"supplyEnd":"2016-02-08T12:03:00+0000",
"logs":
[{"dateTime":"2016-02-02 11:26:18",
"statusChangeDateTime":"2016-02-02 00:00:00",
"user":"tsmith",
"uid":1,
"task":"TESTING",
"info":"state changed to 'Y'",
"x":456123,
"y":362514,
"id_log":28294},
{“dateTime":"2016-02-02 10:54:34",
"statusChangeDateTime":"2016-02-02 10:54:00",
"user":"tsmith",
"uid":1,
"task":"TESTING",
"info":"T Smith changed area.",
"x":452356,
"y":325489,
"id_log":28291
},.....
没有键,因为第一部分由12个值作为标题形成,然后日志形成每个标题的值数组。我使用下面的代码返回我的JSON对象,从我的Web服务调用中解析数据对象。
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
我可以使用下面的代码看到数据的返回值
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
然后我尝试使用以下代码等代码为“' name'”提取值。但它不起作用
if let name = json["name"] as? [[String: AnyObject]] {}
如何遍历我的json对象以从头部和日志数组中获取数据?
答案 0 :(得分:1)
似乎json
对象是一个字典数组,所以你应该这样做:
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? Array<Dictionary<String, AnyObject>> {
for item in json {
if let dict = item as? Dictionary<String, AnyObject> {
print(dict["name"])
}
}
}
转换应该是AnyObject
,因为有时价值为String
,例如dict["name"] == "CONTROL TEST"
,但dict["logs"]
为Array<Dictionary<String, String>>
。你看到了吗?