2012-07-09 87 views
1

的json:NSCFString 0x2749a0 valueForUndefinedKey这个类不是键值编码兼容的关键数据

{ 
"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。

回答

5

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

您需要访问下的关键args存储NSArray,然后拉出第一个项目(这是一个字符串),则该字符串转换成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"}] 
} 
+0

我的NSLog resultdata是的NSDictionary – pengwang 2012-07-09 11:50:32

+0

忘记日志,什么是调试器说什么?你可以只存储一个看起来像字典的字符串。 – coneybeare 2012-07-09 11:57:06

+0

debuger是:resultdata \t __NSCFConstantString * \t 0x3fa40580 – pengwang 2012-07-09 12:00:25

相关问题