小编典典

解析NSJSONReadingAllowFragments

json

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

我收到无效的参数异常:

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

如何读取此值?


阅读 396

收藏
2020-07-27

共1个答案

小编典典

看来您的服务器发送了“嵌套JSON”:jsonResponse是JSON 字符串 (不是 dictionary
)。该字符串的值再次是表示字典的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"];
2020-07-27