我从服务器发送这个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" } ] } } }
我使用以下代码来解析上述json到NSDictionary对象.
NSMutableDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
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页面使用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); }
我发现在第一个角色和最后一个角色#65279之后.经过一个快速的谷歌搜索,我发现What is this char? 65279,这被确定为byte order mark.
在我的情况下,我可以通过打开并保存所有包含的PHP文件来解决这个问题,使用一个文本编辑器提供了一个选项来使用“没有BOM的UTF-8编码”编码.有关PHP端的更多信息,请参阅How to avoid echoing character 65279 in php?