October 2013
Intermediate to advanced
1053 pages
28h 7m
English
You have JSON data, and you want to deserialize it into a dictionary or an array.
Use the JSONObjectWithData:options:error: method of
the NSJSONSerialization class.
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;idjsonObject=[NSJSONSerializationJSONObjectWithData:jsonDataoptions:NSJSONReadingAllowFragmentserror:&error];if(jsonObject!=nil&&error==nil){NSLog(@"Successfully deserialized...");if([jsonObjectisKindOfClass:[NSDictionaryclass]]){NSDictionary*deserializedDictionary=jsonObject;NSLog(@"Deserialized JSON Dictionary = %@",deserializedDictionary);}elseif([jsonObjectisKindOfClass:[NSArrayclass]]){NSArray*deserializedArray=(NSArray*)jsonObject;NSLog(@"Deserialized JSON Array = %@",deserializedArray);}else{/* Some other object was returned. We don't know how todeal with this situation as the deserializer onlyreturns dictionaries or arrays */}}elseif(error!=nil){NSLog(@"An error happened ...
Read now
Unlock full access