11.10. Deserializing JSON into Arrays and Dictionaries

Problem

You have JSON data, and you want to deserialize it into a dictionary or an array.

Solution

Use the JSONObjectWithData:options:error: method of the NSJSONSerialization class.

Discussion

If you already have serialized your dictionary or array into a JSON object (encapsulated inside an instance of NSData; see Recipe 11.9), you should be able to deserialize them back into a dictionary or an array, using the JSONObjectWithData:options:error: method of the NSJSONSerialization class. The object that is returned back by this method will be either a dictionary or an array, depending on the data that we pass to it. Here is an example:

/* Now try to deserialize the JSON object into a dictionary */
        error = nil;
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:jsonData
                         options:NSJSONReadingAllowFragments
                         error:&error];

        if (jsonObject != nil && error == nil){

            NSLog(@"Successfully deserialized...");

            if ([jsonObject isKindOfClass:[NSDictionary class]]){

                NSDictionary *deserializedDictionary = jsonObject;
                NSLog(@"Deserialized JSON Dictionary = %@",
                      deserializedDictionary);

            }
            else if ([jsonObject isKindOfClass:[NSArray class]]){

                NSArray *deserializedArray = (NSArray *)jsonObject;
                NSLog(@"Deserialized JSON Array = %@", deserializedArray);

            }
            else {
                /* Some other object was returned. We don't know how to
                 deal with this situation as the deserializer only
                 returns dictionaries or arrays */
            }
        }
        else if (error != nil){
            NSLog(@"An error happened ...

Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.