NSJSONSerialization返回NULL的错误

时间:2015-07-01 16:16:13

标签: 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"}

但是我收到了一个奇怪的错误代码:

domain:(null) - 代码:0

有人可以告知造成这种情况的原因吗?

1 个答案:

答案 0 :(得分:1)

刚刚在我的模拟器上测试了代码。它的工作。您需要检查是否从服务器获取数据。 如果你想测试解析的东西,你可以做一件事 - 只需将数据存储在json文件中并将其保存在app bundle中,假设文件为“data.json” 并调用以下方法,您将获得肯定的数据。

function changeddl($this){
           var item = $('#bedrooms option:selected').text()
           $("#divprice").text($this.value>0?(item +"- price: $ " + $this.value):"");
        };