NSJSONSerialization如果json对象有一些垃圾值,则JSONObjectWithData返回null

时间:2013-05-15 05:43:40

标签: iphone objective-c nsjsonserialization

我正在使用以下代码片段来解析网址中的JSON对象。

   NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlAddress] options:NSDataReadingUncached error:&error];
    if (error != nil) {
        NSLog(@"%@",[error localizedDescription]);        
    }   else {
        NSLog(@"No Error: %@", data);  //looks good here. console displays the raw data 
    }

    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    if (error != nil) {
        NSLog(@"%@",[error localizedDescription]);
        return nil;

    }   else {
        NSLog(@"No Error: %@", [result objectForKey:@"exams"]); //console displays the value ("No Error: value for key...") unless a degree symbol is present in which case it displays No Error: (null)

    }

我有10个urlAddresses,7个URL JSONObjectWithData返回json对象。剩下的3个URL JSONObjectWithData返回null。我试图在safari中打开这个url。我看到了一些垃圾字符。我怀疑这个垃圾字符有问题。如何解决这个问题?

我已经看到这个“JSONObjectWithData returns null if degree symbol is in json object”链接类似。建议使用unicode转义序列。如何使用这个“unicode转义序列”来解决我的问题。

2 个答案:

答案 0 :(得分:2)

我同意,如前所述存在编码问题。

参考RFC 4627,第1章,JSON字符串“[...]是零个或多个Unicode字符序列[...]”。 参考RFC 4627,第3章“JSON文本应该用Unicode编码。默认编码是UTF-8。” 你得到的,可能不是unicode。 (请先检查 。)

您有几种方法可以解决这个问题:

a)在厚纸上打印出RFC 4627。去找那个负责发送这个回复的人,然后敲打他的头,直到他说“我会尊重RFC 4627”。 (这是极少数情况之一,其中暴力 是一种解决方案。)

b)如果您知道使用的编码,请从数据中创建一个字符串,然后将其重新编码为unicode。然后使用NSJSONSerializer扫描编码数据。

c)手动更换坏码的出现。

答案 1 :(得分:1)

消除JSON对象中的垃圾字符{{3p>