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];

1 Comment »

  1. vivar said,

    August 4, 2009 @ 11:32 am

    Hi,

    I’m trying to do something similar. On the server-side I am using PHP 5 / MySQL 5. I am testing with data that is just a list of names (‘Andy’,’Alex’,’Bob’,’Billy’,’Chris’…etc.). So, I query my database, via PHP, and hold the results in an array.

    The part that I am struggling with is the following: when I bring the JSON encoded object into objective C, I want to be able to create sections in my tableview (ie. ‘A’, ‘B’ etc.) for the names and place those names into the appropriate section (ie. Section ‘A’ should have ‘Andy’,’Alex’. Section ‘B’ should have ‘Bob’,’Billy’ etc.). I think that it might be easier to setup the key values in PHP then encode the array with JSON and call it from the iphone app.

    I have seen examples of doing this using plists, but none using ‘real data’ .

    Any help would be appreciated,
    Vivar

RSS feed for comments on this post · TrackBack URI

Leave a Comment