我在 AppDelegate.m
中有这段代码:
NSError *error;
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"City" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSArray *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:&error];
NSLog(@"data : %@",data);
NSLog(@"json : %@",json[0]);
并且 data
有内容,但是 NSJSONSerialization
没有将它存储到变量 json
中(它显示 (null)
)
我的 json 文件内容:
[
“Result”:
{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}
]
我尝试过的事情:
NSDictionary
NSArray
可变和非可变更改了 City.json 位置
不同的选项,例如
NSJSONReadingMutableContainers
NSJSONReadingMutableLeaves
kNilOptions
最佳答案
发生这种情况是因为您的 JSON 格式无效。它不等于数组。你需要有
[
{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}
]
没有 Result
键或更改您的 json 并将代码解析为
{
"Result" : [{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}]
}
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments error:&error];
NSArray *arr = json[@"Result"];
关于ios - NSJSONSerialization 不将数据存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966971/