NSCFString 0x2749a0 valueForUndefinedKey这个类不是键值编码兼

2019-10-16 23:18发布

我的JSON:

{
 "name": "notification",
 "args": [
         "{\"data\":  [{\"foreignId\":\"BF7E9276D8607DA5916F796F9F1B9743_2\",\"id\":\"\",\"img\":{\"small\":\"http://jiepang.com/static/img/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。

Answer 1:

这意味着,你的关键路径是不正确的。 与数组打交道时,因为它是未知的,你需要数组的哪个项目不能使用的关键路径。

您需要访问NSArray下的关键存储args ,然后拉出第一个项目(这是一个字符串),则该字符串转换成NSDictionary ,然后拉出的关键data

更快的方法是,以确保您的JSON格式化好:

{
  "name": "notification",
  "args": {"data": [{"foreignId": "BF7E9276D8607DA5916F796F9F1B9743_2", "id": "", "img":{"small": "http://jiepang.com/static/img/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"}]
}


文章来源: NSCFString 0x2749a0 valueForUndefinedKey this class is not key value coding-compliant for the key data
标签: ios json sbjson