简体   繁体   English

如何解析嵌套的 JSON

[英]How to parse a Nested JSON

Thank you reading my post, I known this topic was asked so many time, and I had saw that but no luck...感谢您阅读我的帖子,我知道这个话题被问了很多次,我看到了但没有运气......

I want to parse a simple JSON string, as followings:我想解析一个简单的JSON字符串,如下:

[
   {
      "id":"1",
      "name_en":"Photography",
      "subchannels":[
         {
            "id":"4",
            "name_en":"John"
         },
         {
            "id":"18",
            "name_en":"Sam"
         }
      ]
   },
   {
      "id":"7",
      "name_en":"Equipment",
      "subchannels":[
         {
            "id":"25",
            "name_en":"ABC Company"
         },
         {
            "id":"40",
            "name_en":"CDE Company"
         }
      ]
   }
]

It had convert this string to NSDictionary它已将此字符串转换为 NSDictionary

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

NSDictionary *testDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&e];

Then I list the Dictionary Key然后我列出字典键

for(id key in testDic) {
        NSLog(@"%@", key);
    }

The result is the entire record as the Dictionary Key, so I can't use [testDic objectForKey:key] to retrieve the value.结果是整个记录作为字典键,所以我不能使用 [testDic objectForKey:key] 来检索值。

How can I get the first row name_en and the second row subchannels value?如何获取第一行 name_en 和第二行子通道值? (is it possible to retrieve easily like xpath in XML?) (是否可以像 XML 中的 xpath 一样轻松检索?)

Thank you for helping.感谢您的帮助。

First of all.首先。 The root object of your model is NSArray object - not `NSDictionary.模型的根对象是NSArray对象 - 而不是 `NSDictionary。 '[]' means array and {} means dictionary. '[]' 表示数组,{} 表示字典。

NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&e];

for (NSDictionary *entry in dataArray) {
  NSString *name = entry[@"name_en"];
  NSArray *subchannels = entry[@"subchannels"]; //array of dictionaries

  NSLog(@"Name %s", name); 

  for  (NSDictionary *subchannel in subchannels) {
     NSLog(@"Subchannels name %@ id: %d", subchannel[@"name"], [subchannel[@"id"] integerValue]);
  }
}

If you want to perform advances JSON parsing I encourage you to look at Mantle github project .如果您想执行高级 JSON 解析,我鼓励您查看Mantle github 项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM