0

以下のような大まかな構造のJSONを返します。プラットフォームの数を数える方法を見つけようとしています(この場合は3つですが、1から20程度の範囲である可能性があります)。JSONをに返し、NSDictionary次のような行を使用して必要なデータを取得しています。

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

上記の場合、セクションnameからを取得しますresultsname複数のプラットフォームがあるので、セクション内のそれぞれを循環するループを構築する必要がありますplatforms。どうすればいいのかよくわかりません。すべての助けに感謝します!

"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;

}

4

1 に答える 1

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
}
于 2012-11-06T09:31:53.067 に答える