【发布时间】:2017-02-02 15:13:58
【问题描述】:
我已经做了一个 web 服务来检索数据的 JSON,如下所示:
(这是存储在变量数据中)
{"0":{"categoryId":"1","category":"Restaurants"},"1":{"categoryId":"2","category":"Attractions"},"type":"1006","status":"OK"}
但是我无法成功检索每个对象,因为我想将它们动态存储到数组中,例如
var categoryIDArray = ["1", "2"];
var categoryArray = ["Restaurants", "Attractions"];
因此,我最初想执行以下逻辑,因为我在 android studio for java 和 cordova for javascript 中做了类似的事情
//try
//{
// for(var i = 0; i < data.count(); i++)
// {
// categoryIDArray[i] = data[i].categoryId;
// categoryArray[i] = data[i].category;
// }
//}
//catch(Exception ex)
//{
// //Catch null pointer or wrong format for json
//}
但是我已经被困在 swift 2 中检索 JSON 的数量了。
//I tried doing the following to see if I am able to retrieve data 0 JSON but it failed
//print(data![0]);
以下代码有效,但只能提取单个数据
do{
let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let test1 = (json!["status"] as? String)!
let test2 = (json!["0"] as? String)!
print(test1) //shows "OK"
print(test2) //shows nil instead of {"categoryId":"1","category":"Restaurants"}
} catch {
print("JSON parse error")
}
有什么建议吗?谢谢!
【问题讨论】:
-
为什么 web 服务会创建一个以整数为键的字典而不是数组?这不是好的 JSON 格式...
-
@EricAya 嗨,可以就一个好的 json 格式提出建议吗?我现在可以进行更改
-
我会为字典使用一个数组,类似于:
{"type": "1006", "status": "OK", "data": [{"categoryId": "1", "category": "Restaurants"}, {"categoryId": "2", "category": "Attractions"}]} -
然后您将 json["data"] 的结果转换为字典数组:
[[String: Any]]并能够循环。 -
@EricAya:这实际上不是一种合法的格式。 JSON 中的字典键必须是字符串。