Andrew Schutts Andrew Schutts - 9 months ago 45
iOS Question

Trying to parse json array returned by a restful web APS for an iOS project

I am trying to parse a JSON array returned by a RESTful web API that looks similiar to the following (using jsonviewer the json is returned as a bunch of dictionaries in an array):

"date": "2011-03-21",
"meal": "BREAKFAST",
"category": "BREAKFAST BAKERY",
"recipe": "213012",
"name": "Aesops Bagels",
"portion": "1",
"unit": "each"},

I am trying to get the "name" information and then store it into an tableview. Here is the code I am using to accomplish that:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
NSArray *allDataArray = [NSJSONSerialization JSONObjectWithData:webData

for (NSDictionary *diction in allDataArray) {
NSDictionary *menuItem = [diction objectForKey:@"menuItem"];
NSString *name = [menuItem objectForKey:@"name"];

[array addObject:name];

[[self MyTableView]reloadData];

The error that I am getting is:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

So I'm pretty sure that there is an error occurring in the line above the for loop, and this is causing the array to try to take
as a value. But any help figuring out what is going wrong/how to successfully parse this json would be extremely appreciated. I am very new to both json, xcode, and iOS so I apologize if I have done anything particularly stupid.

Answer Source

You don't actually have an item called menuItem in your JSON sample. Your code looks as it was written to parse JSON that looks like this:

[{ "menuItem" : { "name" : "Aesops Bagels",

ie, its expecting a "menuItem" key in each dictionary in the list. If you're actually trying to parse the snippet you posted, I think you just need to simplify your loop code from this:

NSDictionary *menuItem = [diction objectForKey:@"menuItem"];
NSString *name = [menuItem objectForKey:@"name"];


NSString *name = [diction objectForKey:@"name"];

You may also want to make sure that name isn't nil before you attempt to add it to your results array, just in case your data has an entry that's missing a name.