December 2012
Intermediate to advanced
834 pages
27h
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 9.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 either be 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=(NSDictionary*)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 to dealwith this situation, as the deserializer returns only dictionariesor arrays */}}elseif(error!=nil){NSLog
Read now
Unlock full access