How to parse JSON in iOS App How to parse JSON in iOS App arrays arrays

How to parse JSON in iOS App


I haven't done JSON parsing myself in an iOS App, but you should be able to use a library like the json-framework. This library will allow you to easily parse JSON and generate json from dictionaries / arrays (that's really all JSON is composed of).

SBJson docs:

JSON is mapped to Objective-C types in the following way:

  • null -> NSNull
  • string -> NSString
  • array -> NSMutableArray
  • object -> NSMutableDictionary
  • true -> NSNumber's -numberWithBool:YES
  • false -> NSNumber's -numberWithBool:NO
  • integer up to 19 digits -> NSNumber's -numberWithLongLong:
  • all other numbers -> NSDecimalNumber

Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber instances. However, since these are initialised with the -initWithBool: method they round-trip back to JSON properly. In other words, they won't silently suddenly become 0 or 1; they'll be represented as 'true' and 'false' again.

As an optimisation integers up to 19 digits in length (the max length for signed long long integers) turn into NSNumber instances, while complex ones turn into NSDecimalNumber instances. We can thus avoid any loss of precision as JSON allows ridiculously large numbers.

@page objc2json Objective-C to JSON

Objective-C types are mapped to JSON types in the following way:

  • NSNull -> null
  • NSString -> string
  • NSArray -> array
  • NSDictionary -> object
  • NSNumber's -initWithBool:YES -> true
  • NSNumber's -initWithBool:NO -> false
  • NSNumber -> number

@note In JSON the keys of an object must be strings. NSDictionary keys need not be, but attempting to convert an NSDictionary with non-string keys into JSON will throw an exception.

NSNumber instances created with the -numberWithBool: method are converted into the JSON boolean "true" and "false" values, and vice versa. Any other NSNumber instances are converted to a JSON number the way you would expect.

Tutorials

Are there any tutorials? Yes! These are all tutorials provided by third-party people:

JSON Framework for iPhone - a Flickr tutorial in three parts by John Muchow. JSON Over HTTP On The iPhone - by Dan Grigsby. AS3 to Cocoa touch: JSON by Andy Jacobs.

There are other libraries you can check out as well like TouchJSON, JSONKit, Yet Another JSON Library


NSJSONSerialization does the job of converting your JSON data into usable data structures as NSDictionary or NSArray very well. I recommend it, even more because it is part of the Cocoa public interface and it is maintained by Apple.

However, if you want to map the content of your JSON to your Objective-C objects, you will have to map each attribute from the NSDictionary/NSArray to your object property. This might be a bit painful if your objects have many attributes.

In order to automatise the process, I recommend you to use the Motis category (personal project) on NSObject to accomplish it, thus it is very lightweight and flexible. You can read how to use it in this post. But just to show you, you just need to define a dictionary with the mapping of your JSON object attributes to your Objective-C object properties names in your NSObject subclasses:

- (NSDictionary*)mjz_motisMapping{    return @{@"json_attribute_key_1" : @"class_property_name_1",             @"json_attribute_key_2" : @"class_property_name_2",              ...             @"json_attribute_key_N" : @"class_property_name_N",            };}

and then perform the parsing by doing:

- (void)parseTest{    NSData *data = jsonData; // <-- YOUR JSON data     // Converting JSON data into NSArray (your data sample is an array)    NSError *error = nil;    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];    if (error)        return; // <--- If error abort.    // Iterating over raw objects and creating model instances    NSMutableArray *parsedObjects = [NSMutableArray array];    for (NSDictionary *rawObject in jsonArray)    {        // Creating an instance of your class        MyClass instance = [[MyClass alloc] init];        // Parsing and setting the values of the JSON object        [instance mjz_setValuesForKeysWithDictionary:rawObject];        [parsedObjects addObject:instance];    }    // "parseObjects" is an array with your parsed JSON.    // Do whatever you want with it here.}

The setting of the properties from the dictionary is done via KeyValueCoding (KVC) and you can validate each attribute before setting it via KVC validation.


I recently had to do this. After looking at the various options out there, I threw JSONKit into my app (I found it on a JSON discussion on StackOverflow). Why?A) It is VERY VERY simple. I mean, all it has is the basic parsing/emitting functions, what more do you need?B) It is VERY VERY fast. No overhead - just get the job done.

I should note, I had never done JSON before - only heard of the term and didn't even know how to spell it. I went from nothing, to a working app, in about 1 hour. You just add one class to your app (the .h, .m), instantiate it, and call the parser to a dictionary object. Voila. If it contains an array, you just get the objectForKey, cast it as an NSArray. It's really hard to get simpler than that, and very fast.