I have this code in AppDelegate.m
:
我在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]);
And data
has content but NSJSONSerialization
is not storing it into variable json
(it shows (null)
)
数据有内容,但NSJSONSerialization没有将它存储到变量json中(它显示(null))
My json file content :
我的json文件内容:
[
“Result”:
{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}
]
Things i have tried:
我尝试过的事情:
-
NSDictionary
NSArray
both mutable and non mutableNSDictionary NSArray既可变又不可变
-
Changed City.json location
改变了City.json的位置
-
Different options like
NSJSONReadingMutableContainers
NSJSONReadingMutableLeaves
kNilOptions
不同的选项,如NSJSONReadingMutableContainers NSJSONReadingMutableLeaves kNilOptions
2 个解决方案
#1
2
It happened because your JSON has invalid format. It not equal array. You need have
这是因为您的JSON格式无效。它不等于数组。你需要
[
{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}
]
without Result
key or change your json and parse code to
没有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"];
#2
0
The method jsonObjectWithData
will fail if the JSON data is badly formed.
如果JSON数据格式错误,jsonObjectWithData方法将失败。
There must be something wrong with the syntax of your JSON data. You can convert the NSData to a string and log that. You might also check the error you're getting back from the function.
JSON数据的语法肯定有问题。您可以将NSData转换为字符串并记录该字符串。您还可以检查从函数中返回的错误。
#1
2
It happened because your JSON has invalid format. It not equal array. You need have
这是因为您的JSON格式无效。它不等于数组。你需要
[
{
"ID":"3",
"Name":"Ambegaon",
"Distid":"1050114"
},
{
"ID":"4",
"Name":"Aundh",
"Distid":"1050114"
}
]
without Result
key or change your json and parse code to
没有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"];
#2
0
The method jsonObjectWithData
will fail if the JSON data is badly formed.
如果JSON数据格式错误,jsonObjectWithData方法将失败。
There must be something wrong with the syntax of your JSON data. You can convert the NSData to a string and log that. You might also check the error you're getting back from the function.
JSON数据的语法肯定有问题。您可以将NSData转换为字符串并记录该字符串。您还可以检查从函数中返回的错误。