How to parse a JSON URL in iOS and Cocoa

Both Cocoa and iOS have built-in methods to parse (and generate) JSON data using NSJSONSerialization.

Most commonly you’ll want to call a URL with parameters which will return some data. You take this output and tell Objective-C that it’s JSON, then typecast the return to an array or a dictionary which in turn lets you access the data. It’s genius!

Here’s an example:

// create the URL we'd like to query
NSURL *myURL = [[NSURL alloc]initWithString:@"http://domain.com/jsonquery"];
        
// we'll receive raw data so we'll create an NSData Object with it 
NSData *myData = [[NSData alloc]initWithContentsOfURL:myURL];
        
// now we'll parse our data using NSJSONSerialization
id myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
        
// typecast an array and list its contents
NSArray *jsonArray = (NSArray *)myJSON;
        
// take a look at all elements in the array
for (id element in jsonArray) {
    NSLog(@"Element: %@", [element description]);            
}

What you’ll get back depends on your individual JSON structure of course. This can be quite complex, for example you could receive an array full of dictionaries, each of which could be full of dictionaries. JSON data can be mapped to an NSArray, NSDictionary, NSNumber and NSNull.

Once you have access to the top level elements you can then loop through each one, examining what’s in it and access what you need.

Further Reading





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.