Convert json to NSDictionary
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 }