0

我正在返回具有如下结构的粗略结构的 JSON,并且我试图弄清楚如何计算有多少平台(在本例中为三个,但可能是 1 到 20 左右)。我已将 JSON 返回到 an 中NSDictionary,并正在使用诸如此类的行来检索我需要的数据:

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

在上述情况下,它将nameresults部分中获取。由于有多个平台,我需要构建一个循环来循环遍历name该部分内的每个平台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 回答