2012-11-06 26 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