gpt4 book ai didi

ios - 统计某个对象在 JSON 查询中出现的次数

转载 作者:行者123 更新时间:2023-11-28 22:45:42 25 4
gpt4 key购买 nike

我返回的 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;

最佳答案

“平台”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
}

关于ios - 统计某个对象在 JSON 查询中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13247912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com