Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/117.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 解析NSJSONReadingAllowFragments_Ios_Json_Nsdictionary - Fatal编程技术网

Ios 解析NSJSONReadingAllowFragments

Ios 解析NSJSONReadingAllowFragments,ios,json,nsdictionary,Ios,Json,Nsdictionary,我在我的应用程序中收到一些json数据: NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonResponse options:NSJSONReadingAllowFragments error:nil]; NSLog(@"json :%@", json); 哪些日志: json :{ "email" : "/apex/emailAttachment?documentId=00PZ0

我在我的应用程序中收到一些json数据:

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonResponse options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"json :%@", json);
哪些日志:

json :{
  "email" : "/apex/emailAttachment?documentId=00PZ0000000zAgSMAU&recipientId=003Z000000XzHmJIAV&relatedObjectId=a09Z00000036kc8IAA&subject=Pricing+Comparison"
}
这正是我想要的

然而,当我去阅读电子邮件的价值时

[json objectForKey:@“电子邮件”]

我收到无效参数异常:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“*-[NSDictionary initWithDictionary:copyItems:]:dictionary参数不是NSDictionary”


如何读取此值?

您的服务器似乎发送了“嵌套JSON”:
jsonResponse
是JSON字符串(不是 字典)。该字符串的值也是表示字典的JSON数据

在这种情况下,必须将JSON反序列化两次:

NSString *jsonString = [NSJSONSerialization JSONObjectWithData:jsonResponse options:NSJSONReadingAllowFragments error:nil];
NSData *innerJson = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:innerJson options:0 error:nil];

NSString *email = jsonDict[@"email"];

“json”对象显然不是字典,因此出现了错误

您正在将
NSJSONReadingAllowFragments
标志传递给
JSONObjectWithData:options:error:
,其中显示:

指定解析器应允许非NSArray或NSDictionary实例的顶级对象

您需要检查从方法返回的对象的类类型


此外,您还错误地认为您将从方法调用中获得一个可变实例。如果希望返回可变实例,则需要对可变数组/DIC使用
NSJSONReadingMutableContainers
,或对可变字符串使用
NSJSONReadingMutableLeaves
默认情况下
[NSJSONSerialization JSONObjectWithData:
返回不可变实例。如果你想要一个可变的dict,你需要修改你的选项标志以包括
NSJSONReadingMutableContainers
@BradAllred:这当然是正确的,但是在这种情况下,你可以从NSLog输出中看到
json
根本不是字典。字典会打印成
{email=…“}
,而不是
{“email”:}
。对了,我想试着回答这个问题,而不是指出他的代码中的一个缺陷。尽管他向一个非口述者发送
objectForKey:
,这确实是他的问题。