解析NSJSONReadingAllowFragments

我在我的应用程序中收到一些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:@"email"]

我收到一个无效的参数exception:

因未捕获的exception’NSInvalidArgumentException’而终止应用程序,原因:’ * – [NSDictionary initWithDictionary:copyItems:]:字典参数不是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实例的顶级对象。

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

此外,您会错误地认为您将从方法调用中获取可变实例。 如果你想要返回一个可变实例,你需要为可变数组/ dics使用NSJSONReadingMutableContainers或者为可变字符串使用NSJSONReadingMutableContainers