2012-11-06 24 views
0

我返回JSON,其结构像下面那样粗糙,我试图弄清楚如何计算有多少个平台(在这种情况下,三个,但可以是从1到20左右的任何东西)。我返回的JSON为NSDictionary,并使用线,如这些我取回我需要的数据:计算某个对象在JSON查询中出现的数量

_firstLabel.text = _gameDetailDictionary[@"results"][@"name"]; 

在上述情况下,它会从results节抢name。由于有多个平台,我需要构建一个循环来遍历platforms部分中的每个name。不太确定如何去做。所有帮助赞赏!

"results":{ 
    "platforms":[ 
     { 
      "api_detail_url":"http://", 
      "site_detail_url":"http://", 
      "id":18, 
      "name":"First Name" 
     }, 
     { 
      "api_detail_url":"http://", 
      "site_detail_url":"http://", 
      "id":116, 
      "name":"Second Name" 
     }, 
     { 
      "api_detail_url":"http://", 
      "site_detail_url":"http://", 
      "id":22, 
      "name":"Third Name" 
     } 
    ], 

编辑:这是我的fetchJSON方法:

- (NSDictionary *) fetchJSONDetail: (NSString *) detailGBID { 

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: YES]; 

    NSString *preparedDetailURLString = [NSString stringWithFormat:@"http://whatever/format=json", detailGBID]; 
    NSLog(@"Doing a detailed search for game ID %@", detailGBID); 

    NSData *jsonData = [NSData dataWithContentsOfURL: [NSURL URLWithString:preparedDetailURLString]]; 

    _resultsOfSearch = [[NSDictionary alloc] init]; 
    if (jsonData) { 
     _resultsOfSearch = [NSJSONSerialization JSONObjectWithData: jsonData 
                  options: NSJSONReadingMutableContainers 
                  error: nil]; 
    } 

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: NO]; 

    NSString *results = _resultsOfSearch[@"number_of_page_results"]; 
    _numberOfSearchResults = [results intValue]; 

    NSArray *platforms = [_resultsOfSearch valueForKey:@"platforms"]; 
    int platformsCount = [platforms count]; 
    NSLog(@"This game has %d platforms!", platformsCount); 

    return _resultsOfSearch; 

}

回答

2

的 “平台” JSON字段是一个数组,所以假设使用的东西,就像你去序列化JSON,

NSMutableDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:resultsData options:NSJSONReadingMutableContainers error:&error]; 

然后,您可以指定平台,一个NSArray,

NSDictionary *results = [responseJSON valueForKey:@"results"]; 

NSArray *platforms = [results valueForKey:@"platforms"]; 

...并发现通过平台的数量,

int platformsCount = [platforms count]; 

在你的情况,你想通过平台进行迭代,你可以使用,

for (NSDictionary *platform in platforms) 
{ 
    // do something for each platform 
} 
+0

看起来不错,但似乎没有工作。我已经添加了上面的方法,我已经添加了NSArray和int,但下面的NSLog每次都返回零。 “平台”位于JSON嵌套中的位置是否有关系,还是只是在可能的位置寻找它? – Luke

+0

我的错误是,我没有从最初的字典中提取@“results”字段以将其降低到一个级别。我编辑了我的答案。 – Snips

+0

完美!谢谢 :) – Luke