How to parse a JSON URL in iOS and Cocoa

- by

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



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.