如何在目标 C 中解析嵌套的 JSON 数组


How to parse nested JSON arrays in Objective C

我有这个JSON树,我需要按类别键对数组进行分组。(在此示例中,:","1","2","3"和"serf"是类别的值名称。我正在使用 NSJSONSerialization 序列化 JSON,但无法按照我想要的方式解析它。这是我的一些代码:

NSData *data2=[NSData dataWithContentsOfURL:url2];
result2=[NSJSONSerialization JSONObjectWithData: data2
                                        options: NSJSONReadingMutableContainers
                                          error: nil];
NSLog(@"button data: %@", result2);
for (NSDictionary *strh in [result2 objectForKey:@"template"]) {
    //the json struct above is called result2 here
    //now i need to parse any category with their names..           
}  

相关:这是我关于如何在 PHP 中创建具有键值匹配的多维数组的问题。

查看输出,您有一个字典,其中包含一个名为 template 的键和一个名为 version 的键。 键template的对象本身就是一个字典,其中包含类别的键。 以下代码:

id foo = [[result2 objectForKey: @"template"] objectForKey: @""];

foo设置为包含 ID 为 52、19、2、22 的项目的数组。

类别 1、2、3 更棘手,因为键是数字还是字符串并不明显。 它们可能是字符串,因为 JSON 中的键必须是字符串,所以

id bar = [[result2 objectForKey: @"template"] objectForKey: @"1"];

bar设置为包含 ID 为 28、1、25 的项目的数组。