Convert json to NSDictionary

walden systems, objective c, geolocation, ios, CLLocationManager, desiredAccuracy, distanceFilter, startUpdatingLocation, stopUpdatingLocation, delegate, iphone, picture, screen, swipe. nsdictionary, nsmutabledictionary, json, deserialize, serialize, key, value, iphone
Objective-C defines a small but powerful set of extensions to the ANSI C programming language that enables sophisticated object-oriented programming. Objective-C is the native language for Cocoa programming—it’s the language that the frameworks are written in, and the language that most applications are written in. You can also use some other languages—such as Python and Ruby—to develop programs using the Cocoa frameworks. It’s useful, though, to have at least a basic understanding of Objective-C because Apple’s documentation and code samples are typically written in terms of this language.

Sometimes you receive json data and you need to convert it to NSDictionary on your iPhone or iPad app. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to convert json data to NSDictionary.

Strategy to convert json data to NSDictionary is fairly simple: First, we need to deserialize json data to a foundation object. Second, we need to check if json data received is a key value pair like NSDictionary. Third, create a NSMutableDictionary to add the values. Fourth, add the key values to NSMutableDictionary.

Here are actual code samples:

The first thing you need to do is deserialize the json data, to do so, use the following line:

1    id        data ;
2    data = [ NSJSONSerialization JSONObjectWithData : JSONDATA options : NSJSONReadingAllowFragments error : &err ] ;

Then you need to check if data is a key-value pair :

1    if ( [ data isKindOfClass : [ NSDictionary class  ]] && err == nil )


Then you need to create a NSMutableDictionary to store the data :

1    NSMutableDictionary *      someDict ;
2    someDict = [ [ NSMutableDictionary alloc ] init ] ;

Then you will need to add the key value to the NSDictionary :

1    someDict = data ;

So, this is how a final code for converting json to NSDictionary will look like:

1     id                         data ;
2     NSMutableDictionary *      someDict ;
3 
4     data = [ NSJSONSerialization JSONObjectWithData : JSONDATA options : NSJSONReadingAllowFragments error : &err ] ;
5     if ( [ data isKindOfClass : [ NSDictionary class  ]] && err == nil )
6     {
7          someDict = [ [ NSMutableDictionary alloc ] init ] ;
8          someDict = data ;
9     }