我有这个JsonResponse:
...id = 7;
levels = (
{
name = "name";
"unique_id" = 23223;
},
{
name = "name";
"unique_id" = d32432;
},
{
name = "name";
"unique_id" = 324;
},
{
name = "name";
"unique_id" = 234;
}
);
我正在使用它来获取结果作为字典:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
我的问题是我如何解析 levels 数组 - 迭代对象并获取数组大小
基本上你只是遍历它们:
if(jsonResult)
{
let levels = jsonResult! as NSDictionary;
for item in levels {
let obj = item as NSDictionary
let name = obj["name"] as NSString;
let uniqueId = obj["unique_id"] as NSNumber;
}
}
我建议在使用 JSON 时尽可能多地使用类型安全。下面是一个(未经测试的)示例,向您展示如何安全地转换数据:
if let levels = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? [[String: AnyObject]] {
for elem in levels {
let name = elem["name"] as? NSString
let uniqueId = elem["unique_id"] as? NSNumber
}
}