Hedam
Hedam

Reputation: 2249

JSON not working as expected on iOS

I'm currently trying to parse this JSON

[{"id":"1","dish_name":"Pasta & ketchup","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKetchup\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"},{"id":"2","dish_name":"Pasta & Kødsovs","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKødsovs\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"}]

But it fails and crashes with this code

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
    NSError *error = NULL;

    NSDictionary* json = [NSJSONSerialization
                      JSONObjectWithData:responseData
                      options:kNilOptions
                      error:&error];
    recipes = [[NSArray alloc] initWithArray:[json objectForKey:@"dish_name"]];
    [uit reloadData];
}

Do someone have any clue, why it crashes with error -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8077240 ?

Thanks in advance.

Upvotes: 1

Views: 463

Answers (2)

user529758
user529758

Reputation:

The error message beginning with [__NSCFArray objectForKey:] means that you have an NSArray (the root object of the JSON is an array - notice the opening and closing square brackets) and you're trying to treat it as a dictionary. All in all,

recipes = [[NSArray alloc] initWithObject:[json objectForKey:@"dish_name"]];

should be

recipes = [[NSArray alloc] initWithObject:[[json objectAtIndex:0] objectForKey:@"dish_name"]];

Note that there are two objects in the array, so you might want to use [json objectAtIndex:1] as well.

Edit: if you have a dynamic number of recipes, you can do this:

recipes = [[NSMutableArray alloc] init];
for (NSDictionary *dict in json) {
    [recipes addObject:[dict objectForKey:@"dish_name"]];
}

Upvotes: 2

Michael Dautermann
Michael Dautermann

Reputation: 89509

If your json NSDictionary were a real & valid NSDictionary object, your call to this:

[json objectForKey:@"dish_name"]

should return exactly this:

"Pasta & ketchup"

Which is definitely not an array. It's a NSString object.

Which would be why the call to "initWithArray" is bombing.

Upvotes: 1

Related Questions