JSON 文本未以数组或对象开头,并且没有设置允许片段的选项 [英] JSON text did not start with array or object and option to allow fragments not set
问题描述
我正在从服务器发送这个 json 响应,以请求我的 IOS 7 应用程序.
I'm sending this json response from server for a request to my IOS 7 app.
{
"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"
}
]
}
}
}
我使用以下代码将上述 json 解析为 NSDictionary 对象.
I use the following code for parsing the above json to NSDictionary object.
NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
但是我在上面的代码中遇到了这个错误.
But I'm getting this error on the above code.
Error Domain=NSCocoaErrorDomain Code=3840 "操作不能完全的.(Cocoa 错误 3840.)"(JSON 文本未以数组或允许未设置片段的对象和选项.) UserInfo=0x8a8a700{NSDebugDescription=JSON 文本没有以数组或对象开头,并且允许未设置片段的选项.}
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8a8a700 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
推荐答案
我在从 php 页面使用提要时遇到了同样的错误.正如您遇到的那样,生成的 json 字符串通过了视觉检查,但无法序列化.我怀疑提要的某个地方有一个隐藏的字符,所以我将每个字符转换为其 unicode 十进制等价物并检查结果:
I ran into the same error when consuming a feed from a php page. Just as you encountered, the resulting json string passed a visual inspection, but would fail to serialize. My suspicion was that there was a hidden character somewhere the feed, so I converted each character to its unicode decimal equivalent and examined the results:
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);
}
我发现在第一个字符之前和最后一个字符之后是#65279.在快速谷歌搜索后,我发现 这是什么字符?65279,其中被标识为字节顺序标记.
I found that before the first character and after the last was the character #65279. After a quick google search I found What is this char? 65279, where this was identified as a byte order mark.
就我而言,我能够通过打开和保存所有包含的 php 文件在源代码处解决此问题,使用的文本编辑器提供了使用无 BOM 的 UTF-8 编码"编码的选项.有关 php 方面的更多信息,请参阅 如何避免在php中回显65279字符?
In my case, I was able to fix this at the source by opening and saving all included php files, using a text editor that provided an option to use the "Encode in UTF-8 without BOM" encoding. For more info on the php side, see How to avoid echoing character 65279 in php?
这篇关于JSON 文本未以数组或对象开头,并且没有设置允许片段的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!