ios - NSJSONSerialization 返回 NULL 错误

标签 ios objective-c json nsjsonserialization

我有以下代码:

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/

相关文章:

iphone - iOS7 中 UITableView 滚动指示器闪烁

ios - 无法识别的选择器发送到实例 0x7fb8bf50b3c0' (Swift/Xcode)

ios - 通过 UITableView 编辑 NSManagedObjects 的现有解决方案?

javascript - 在javascript中读取本地JSON文件

ios - NSUserDefaults 突然停止保存数据

ios - 从 UITabviewController 导航回 Storyboard中的 ViewController

iphone - 防止 iPhone 进入休眠状态

ios - 创建 alertview 并点击标签

javascript - JSON 的自动完成显示不正确 - 我得到值但显示为空白

javascript - JSON 到 HTML 表的转换