2013-03-19 102 views
1

如何循環遍歷目標c中的json [{first set of values},{data->children->data->body}的這一部分?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 
    } 

我怎麼在 「//我在這裏停留」 嗎?

回答

1

您可能需要添加@"children"字典的值在數組中,然後分析該數組進去兒童

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

    // finally parse childrenArray 
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"]); 
}]; 
0

使用NSJSONSerialization嘗試實施這一數據。在這裏你需要通過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"]); 
    } 
}