JSON文本不以数组或对象和选项开头,以允许未设置片段

LvN*_*LvN 12 iphone ios ios7

我正在从服务器发送这个json响应,请求我的IOS 7应用程序.

{
 "root": {
    "success": "1",
    "message": "Successfully retrieved data.",
    "data": {
        "records": [
            {
                "receipt_key": "xxxxxxxx",
                "receipt_id": "xxxxxxxx",
                "store_name": "xxxxxx",
                "amount": "xxxx",
                "date_purchase": "xxxxxxxx",
                "is_processed": "x",
                "created_on": "xxxxxxxx",
                "modified_on": "xxxxxxxx",
                "modified_on_millis": "xxxxxxxx",
                "user_folder": "xxxxxxxx",
                "category_id": "xxxxxxxx",
                "is_deleted": "x",
                "currency_id": "xxxxxxxx"
            }
        ]
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码解析上面的json到NSDictionary对象.

 NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
Run Code Online (Sandbox Code Playgroud)

但是我在上面的代码中遇到了这个错误.

Error Domain = NSCocoaErrorDomain Code = 3840"操作无法完成.(Cocoa error 3840.)"(JSON文本不是以数组或对象开头,而是选项允许未设置片段.)UserInfo = 0x8a8a700 {NSDebugDescription = JSON text没有从数组或对象和选项开始,以允许未设置片段.}

小智 10

从php页面使用Feed时遇到了同样的错误.就像您遇到的那样,生成的json字符串通过了视觉检查,但无法序列化.我的怀疑是在某个地方有一个隐藏的字符,所以我将每个字符转换为其unicode十进制等值并检查结果:

NSString *feedStr = [[NSString alloc] initWithData:feedData encoding:NSUTF8StringEncoding];
for(int i=0; i<[feedStr length]; ++i)
{
    unichar c = [feedStr characterAtIndex:i];
    NSLog(@"decimal char %d", c);
}
Run Code Online (Sandbox Code Playgroud)

我发现在第一个角色之前和最后一个角色之后是角色#65279.快速谷歌搜索后,我发现这是什么字符?65279,其中将其标识为字节顺序标记.

在我的情况下,我能够通过打开并保存所有包含的php文件来解决这个问题,使用文本编辑器提供了一个使用"在没有BOM的UTF-8编码"编码的选项.有关php端的更多信息,请参阅如何避免在php中回显字符65279?