gpt4 book ai didi

ios - Objective-C - 读取 JSON key 时的问题

转载 作者:行者123 更新时间:2023-12-01 19:38:59 24 4
gpt4 key购买 nike

大家好,我正在使用 JSON file在我的 xCode 项目中。

我可以轻松显示各种JSON键,但是当我调用一个键时,它指定我的应用程序崩溃,我不明白为什么......

我非常小心地正确编写了 key ,但它一直在崩溃......

这是我的例子JSON file

{
"Università" : {
"uniID" : {
"latitudine" : 43.115441,
"longitudine" : 12.389587,
"nome" : "Università per stranieri di Perugia",
"regione" : "Umbria"
},
"uniID" : {
"latitudine" : 41.860348,
"longitudine" : 12.496308,
"nome" : "Università degli Studi Internazionali di Roma ( UNINT )",
"regione" : "Lazio"
},
}
}

当我尝试恢复 “姓名” 关键我的应用程序崩溃了,即使我调用 也是如此“纬度” "经度" ETC ...

我在哪里做错了?

这些是我用来读取 JSON 文件的函数
-(void)setupUniversityLocation:(MKMapView *)mapView {

NSDictionary *dict = [self JSONUniversity];
NSArray *universityArray = [[dict objectForKey:@"Università"] objectForKey:@"uniID"];

for (NSDictionary *uni in universityArray) {

NSString *uniname = [uni objectForKey:@"nome"];
NSLog(@"uniname %@",uniname);
}
}

#pragma mark - Read JSON Data University

-(NSDictionary *)JSONUniversity {
NSString *path = [[NSBundle mainBundle] pathForResource:@"university" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

我也想问你如何直接读取 key “姓名” , “纬度” 等等...没有在哪里调用 "uniID" key ?是否可以绕过类别键?

最佳答案

您的 json 文件中没有数组。您应该将 json 文件更改为

{
"Università" : [
{
"latitudine" : 43.115441,
"longitudine" : 12.389587,
"nome" : "Università per stranieri di Perugia",
"regione" : "Umbria"
},
{
"latitudine" : 41.860348,
"longitudine" : 12.496308,
"nome" : "Università degli Studi Internazionali di Roma ( UNINT )",
"regione" : "Lazio"
}
]
}

使用 []显示数组而不是 {}下面的代码将起作用
-(void)setupUniversityLocation:(MKMapView *)mapView {

NSDictionary *dict = [self JSONUniversity];
NSArray *universityArray = [dict objectForKey:@"Università"];

for (NSDictionary *uni in universityArray) {
NSString *uniname = [uni objectForKey:@"nome"];
NSLog(@"uniname %@",uniname);
}
}

#pragma mark - Read JSON Data University

-(NSDictionary *)JSONUniversity {
NSString *path = [[NSBundle mainBundle] pathForResource:@"university" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

关于ios - Objective-C - 读取 JSON key 时的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58237606/

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