我有以下代码:
NSData * jsonData = [NSData dataWithContentsOfURL:location];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data = [newStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
if (jsonError) {
NSLog(@"JSON Error %@", [jsonError localizedDescription]);
}
NSArray * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
正在解析以下 JSON 字符串:
{"author":"Oli Riman","content":"The museum shows us a view of pre-WWI society that includes doubts, fears, political protests etc. through newspaper cartoons of the time. Really interesting for adults who enjoy history. I wouldn't suggest this for kids who haven't studied WWI history or who don't read easily.","rating":"5","placeId":"40","date":"29-June-2015","reviewId":"9905A52D-76B2-4D42-8CA8-9158225C0D07"}
但是我得到了一个奇怪的错误代码:
域:(空)- 代码:0
谁能告诉我这是什么原因造成的?
最佳答案
刚刚在我的模拟器上测试了代码。它的工作。您需要检查是否从服务器获取数据。 如果你想测试解析的东西,你可以做一件事 - 只需将数据存储在 json 文件中并将其保存在应用程序包中就可以说文件是“data.json” 并调用下面的方法,你肯定会得到数据。
- (void)readJsonData {
NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
NSURL *url = [NSURL fileURLWithPath:path];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data
options: NSJSONReadingAllowFragments
error: &error];
NSLog(@"Parsed json data- %@", dict);
}
关于ios - NSJSONSerialization 返回 NULL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31166646/