1

如何[{first set of values},{data->children->data->body}在目标 c 中循环这部分 json?

json是

  [
      {
        "kind": "Listing"
      },
      {
        "kind": "Listing",
        "data": {
          "children": [
            {
              "data": {
                "body": "body1"
              }
            },

            {
              "data": {
                "body": "body2"
              }
            }
          ]
        }
      }
    ]

我目前的代码是

m_ArrList=[[NSMutableArray alloc]init];
    NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:@"surveyquestion.json"];
    NSArray *array=[infomation objectForKey:@"data"];
    int ndx;
    NSLog(@"%@",array);
    for (ndx = 0; ndx < [array count]; ndx++) {
        NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];

        NSArray *string=[stream valueForKey:@"children"];

        //i am stuck here
    }

在“//我被困在这里”时我该怎么办?

4

3 回答 3

1

您可能需要 @"children"在数组中添加字典的值,然后解析该数组以获取子项中的数据

[childrenArray addObject:[stream objectForKey:@"children"]];

   // finally parse childrenArray
于 2013-03-19T10:36:11.830 回答
0

使用NSJSONSerializationtry 来实现这一点。在这里,您需要NSString作为 jsonStr 传递,您需要从文件中读取它。

NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]
                                               options:0
                                                 error:&jsonError];

if(jsonError!=nil)
    NSLog(@"Json_Err: %@",jsonError);

NSArray *array=allValues;

for (int ndx = 0; ndx < [array count]; ndx++) {
    NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
    NSLog(@"%@",[stream objectForKey:@"kind"]);

    NSArray *child = [[stream objectForKey:@"data"] objectForKey:@"children"];

    //i am stuck here

    for(int i =0; i <[child count];i++)
    {
        NSDictionary *childData = (NSDictionary *)[child objectAtIndex:i];
        //NSLog(@"%@",[childData objectForKey:@"data"]);
        NSLog(@"%@",[[childData objectForKey:@"data"] objectForKey:@"body"]);
    }
}
于 2013-03-19T11:20:58.303 回答
0
// You Just need to Implement following Lines and you will get all the data for Key Body in children array
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:@"surveyquestion.json"];

NSArray *string= [[infomation objectForKey:@"data"] objectForKey:@"children"];

[string enumerateObjectsUsingBlock:^(id obj, NSUInteger ind, BOOL *stop){
    NSLog(@"Body : %@",[[obj objectForKey:@"data"] objectForKey:@"body"]);
}];
于 2013-03-19T10:53:26.250 回答