2012-11-06 2 views
0

거친 구조의 JSON을 반환합니다.이 경우 얼마나 많은 플랫폼을 계산할 수 있는지 계산하려고합니다. , 세 개이지만 1 ~ 20 개 정도 될 수 있음). 내가 NSDictionary에 JSON을 반환했습니다 내가 필요로하는 데이터를 검색하기 위해 이들과 같은 라인을 사용하고 있습니다 :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 방법이다 : 그래서 당신은 같은 것을 사용하여 JSON을 해제 연재 한 가정

- (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 필드가 배열입니다,

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는 매번 0을 반환합니다. JSON의 중첩에 '플랫폼'이 어디에 있는지가 중요합니까 아니면 어디에서든지 찾을 수 있습니까? – Luke

+0

실수로, 초기 단계에서 @ "results"필드를 추출하지 않고 레벨을 낮추었습니다. 내 대답을 편집했습니다. – Snips

+0

완벽한! 감사 :) – Luke

관련 문제