我正在尝试使用以下代码使用NSJSONSerialization
输出一些数据。
此日志语句有效NSLog(@"publicData: %@", publicData);
但是当我试图获得字典NSLog(@"data: %@", [dict objectForKey:@"description"]);
我的错误讯息:unrecognized selector sent to instance. Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance...'
我已加入NSLog
输出。
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"http://******.com/api/feed"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSArray *publicData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSLog(@"data from publicData: %@", publicData);
NSDictionary *dict;
for(int i=0; i<[publicData count];i++)
{
dict= [publicData objectAtIndex:i];
NSLog(@"data: %@", [dict objectForKey:@"description"]);
}
publicData: {
data = (
{
address = {
address = "street address";
city = cityname;
lat = "42.000237034667";
lng = "12.492805660226";
province = provincename;
};
"category_id" = 20;
description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
id = 1;
slug = "title-in-en";
title = "title in En";
},
{
address = {
address = "street address";
city = cityname;
lat = "42.000237034667";
lng = "12.492805660226";
province = provincename;
};
"category_id" = 20;
description = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
id = 5;
slug = "title-in-en";
title = "title in En";
},
感谢您的帮助
答案 0 :(得分:1)
我优化了一些codeplasma提供的代码,它看起来像这样:
NSDictionary *publicData = [NSJSONSerialization JSONObjectWithData:response
options:0
error:&jsonParsingError];
NSArray *objects = [publicData objectForKey:@"data"];
for(NSDictionary *element in objects) {
NSLog(@"the description is %@",[element objectForKey:@"description"]);
}
您的publicData为NSDictionary
而不是NSArray
。
答案 1 :(得分:0)
我不知道这是否有效,但你应该尝试用这个代替你的for循环:
for(int i=0; i<[[publicData objectForKey:@"data"] count];i++)
{
dict= [[publicData objectForKey:@"data"] objectAtIndex:i];
NSLog(@"data: %@", [dict objectForKey:@"description"]);
}