Xcode开发工具I love iOSiOS技术专题

解析json的时候报错:Error Domain=NSCocoa

2016-02-16  本文已影响6540人  Code_Ninja

今日在程序中发现一个解析json报错的问题,总是报如下错:

Error Domain=NSCocoaErrorDomain Code=3840 "
The operation couldn’t be completed. (Cocoa error 3840.)"
 (Unexpected end of file during string parse 
(expected low-surrogate code point but did not find one).)
 UserInfo=0x7fc9b3646520 {NSDebugDescription=Unexpected end of 
file during string parse (expected low-surrogate code point but did not
 find one).

搜了下low-surrogate code point发现是缺少低位代理码,导致无法正常解析json数据。

仔细检查了下数据来源发现当用户发布的文字内容是“给自己一个微笑也给他人一个微笑😊😊”时,后台在截取一定长度字符串的时候刚好截取到表情符号的编码位置,导致截取了一部分表情编码给我:


"newContent": {
                "id": "56",
                "title": null,
                "articleThumbImage": null,
                "articleType": null,
                "content": "给自己一个微笑也给他人一个微笑�",
                "weburl": null,
                "action": null,
                "linkEntityId": null,
                "userId": null,
                "userName": null,
                "userGender": null,
                "userIcon": null,
                "userTitle": null,
                "praiseCount": null,
                "commentCount": null,
                "circleName": null,
                "circleThumbImage": null
            },

由此看见content字段中包含了第一个表情的一部分编码,因为缺少后面一部分编码,所以导致iOS这边无法正常解析该json。

这个是我们在截取字符串长度的时候容易忽略考虑到的地方。谷歌搜了下Error Domain=NSCocoaErrorDomain Code=3840关键字,发现之前有人也遇到过类似的问题,但是都不是这个问题,特做此记录,希望能帮到大家。

2016-2-17补充:
由于后台人员不给解决这个问题要客户端自己处理,经过查阅发现JSONKit可以处理这个问题,我暂时就使用了JSONKit来处理这种问题:

id result = [NSJSONSerialization JSONObjectWithData:data options:options error:&error];
if (error) { error = nil; result = [data objectFromJSONDataWithParseOptions:JKParseOptionLooseUnicode error:& error]; 
// use JSONKit }

原文:
NSJSONSerialization - “Unexpected end of file during string parse”

上一篇 下一篇

猜你喜欢

热点阅读