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;
}
看起来不错,但似乎没有工作。我已经添加了上面的方法,我已经添加了NSArray和int,但下面的NSLog每次都返回零。 “平台”位于JSON嵌套中的位置是否有关系,还是只是在可能的位置寻找它? – Luke
我的错误是,我没有从最初的字典中提取@“results”字段以将其降低到一个级别。我编辑了我的答案。 – Snips
完美!谢谢 :) – Luke