O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required