Is the following statement correct, or am I missing something?
You have to check the return object of NSJSONSerialization
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 which breaks if used on the wrong one. For example:
NSMutableArray *jsonObject = [json objectAtIndex:i];
// will break if json is a dictionary
so you have 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 thru stack overflow and Apple documentation and other places and could not find any direct confirmation of the above.
If you are just asking if this is correct or not, yes it is the safe way to process jsonObjects
. It's also how you would do it with other API that returns id
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With