我正在尝试解析一些json,到目前为止我已经:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *results = [json objectForKey:@"d"];
NSString *error = [results objectForKey:@"error"];
NSArray *items = [results objectForKey:@"vehicles"];
NSLog(@"items::%@", items);
for (NSDictionary *item in items) {
IDCard *idcard = [[IDCard alloc] init];
idcard.year = [item objectForKey:@"year"];
idcard.make = [item objectForKey:@"make"];
idcard.model = [item objectForKey:@"model"];
nslog项目是:
items::(
(
{
make = CHEV;
model = MALIBU;
year = 2002;
},
{
make = GMC;
model = SIERRA1500;
year = 1995;
}
)
)
它很好,直到idcard.year = [item objectForKey:@"year"];
它与Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x9fdea80'
崩溃,我不明白为什么这样做。
如果它有助于发布完整的json让我知道,我会。谢谢你能给我的任何帮助。
答案 0 :(得分:1)
@ akashivskyy是对的。在数组中有一个(看似多余的)数组(例如,items数组所在的空容器数组)。您可能需要稍微修改一下JSON吗?但是,如果您只是想避免NSInvalidArgumentException,以下应该做的伎俩 - 而不是
NSArray *items = [results objectForKey:@"vehicles"];
试试这个:
NSArray *items = [[results objectForKey:@"vehicles"] objectAtIndex:0];
答案 1 :(得分:0)
如果你看一下输出的json,你会发现字典存储在一个数组中。
包含所有词典的数组存储在另一个长度为1的数组中。
取代这一行:
for (NSDictionary *item in items) {
这一行:
for (NSDictionary *item in [items objectAtIndex:0]) {
答案 2 :(得分:0)
它的外观类似于Array并包含字典数组,因此如果执行操作,NSArray上的objectForKey将崩溃,并显示错误消息“无法识别的选择器”
试试这个。
NSArray items1 =[items objectAtIndex:0];
for (NSDictionary *item in items1) {
IDCard *idcard = [[IDCard alloc] init];
idcard.year = [item objectForKey:@"year"];
idcard.make = [item objectForKey:@"make"];
idcard.model = [item objectForKey:@"model"];
}
如果上述解决方案不起作用,请将您的JSON字符串粘贴到此处
答案 3 :(得分:0)
常见的陷阱可能是使用arrayWithObjects
代替arrayWithArray