【发布时间】:2012-11-06 09:18:52
【问题描述】:
我返回的 JSON 具有如下所示的粗略结构,我试图弄清楚如何计算有多少平台(在本例中为三个,但可以是 1 到 20 或所以)。我已将 JSON 返回到 NSDictionary 并使用诸如此类的行来检索我需要的数据:
_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;
}
【问题讨论】:
标签: ios json for-loop nsdictionary nsjsonserialization