Object returned from NSJSONSerialization may change

Is the following statement correct, or am I missing something?

You should check the returned NSJSONSerialization object to see if it is a dictionary or an array - you can have

 data = {"name":"joe", "age":"young"} // NSJSONSerialization returns a dictionary 

and

 data = {{"name":"joe", "age":"young"}, {"name":"fred", "age":"not so young"}} // returns an array 

Each type has a different access method that breaks if used incorrectly. For example:

 NSMutableArray *jsonObject = [json objectAtIndex:i]; // will break if json is a dictionary 

so you need to do something like -

  id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; if ([jsonObjects isKindOfClass:[NSArray class]]) NSLog(@"yes we got an Array"); // cycle thru the array elements else if ([jsonObjects isKindOfClass:[NSDictionary class]]) NSLog(@"yes we got an dictionary"); // cycle thru the dictionary elements else NSLog(@"neither array nor dictionary!"); 

I had a good look through the stack overflow, Apple documentation and other places, and I could not find direct confirmation above.

+7
source share
1 answer

If you're just asking if this is correct or not, yes, this is a safe way to handle jsonObjects . Just like you do with another API that returns id .

+5
source

All Articles