Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object returned from NSJSONSerialization can vary

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.

like image 282
user1705452 Avatar asked Oct 18 '12 03:10

user1705452


1 Answers

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.

like image 197
John Estropia Avatar answered Sep 29 '22 05:09

John Estropia