Archive for January, 2009

iPhone SDK: Parsing semi-complex JSON objects

Since this seems to be quite common for newcomers to Objective-C / iPhone development, here’s another example on how to parse a semi-complex JSON object. This was asked as a comment on a previous post, but I think that deserves its own space.

The JSON object looks something like the following:

{"start":0,
 "stat":"ok",
 "locations":[{"name":"Pensacola, FL",
               "place_id":"qQ7Vig2bBZsZCy82",
               "woeid":2470377}],
 "count":3,
 "total":3,
 "query":"address=Pensacola"}

So you can quickly see that it’s an object, with a “locations” entry that contains an array of objects. This looks like an object that represents the search results for a location from some web service.

I will parse that complex object by creating separate variables to hold specific parts of the object, but there are simpler ways to do this. In this example, I want to get the value for the “name” key in the first item of the “locations” array.

// jsonString contains the actual JSON output from your web service
SBJSON *json = [[SBJSON alloc] init];
NSError *error = nil;
// object containing full results
NSDictionary *results = [json objectWithString:jsonString error:&error];
// array just for the "location" results
NSArray *locations = [results objectForKey:@"locations"];
// first location in your array
NSDictionary *firstLocation = [locations objectAtIndex:0];
// finally, the name key
NSString *name = [firstLocation objectForKey:@"name"];
[json release];