Reputation: 3454
I am trying to parse some json, so far I have:
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"];
the nslog of items is this:
items::(
(
{
make = CHEV;
model = MALIBU;
year = 2002;
},
{
make = GMC;
model = SIERRA1500;
year = 1995;
}
)
)
its fine til it gets to the idcard.year = [item objectForKey:@"year"];
and it crashes with Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x9fdea80'
and I dont understand why its doing this.
If it helps to post the full json let me know and I will. Thank you for any help you can give me.
Upvotes: 0
Views: 6924
Reputation: 23282
common pitfall maybe using arrayWithObjects
instead arrayWithArray
Upvotes: 0
Reputation: 961
@ akashivskyy is right. You have an (seemingly redundant) array within an array (e.g. empty container array inside which the items array is residing). You need to look at modifying the JSON a bit, perhaps? However, if you just want to avoid the NSInvalidArgumentException, the following should do the trick- instead of
NSArray *items = [results objectForKey:@"vehicles"];
Try this:
NSArray *items = [[results objectForKey:@"vehicles"] objectAtIndex:0];
Upvotes: 1
Reputation: 1269
Its look like items is Array and contains Array of dictionary so if you perform operation objectForKey on NSArray will crash with error message "Unrecognized selector"
try this.
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"];
}
In case above solution not works then please paste your JSON string here
Upvotes: 0
Reputation: 6404
If you look at the outputed json, you'll se that the dictionary is stored within an array.
The array containing all the dictionaries is stored within another array of length 1.
Replaced this line:
for (NSDictionary *item in items) {
with this line:
for (NSDictionary *item in [items objectAtIndex:0]) {
Upvotes: 0