7

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
user1705452
  • 116
  • 3
  • You didn't mention what problem was going on with your code. – John Estropia Oct 18 '12 at 03:31
  • The problem is if you get a dictionary back and use an array method to access it an exception is thrown. I think you need to check the return object type to fix this, but would like confirmation that this is the correct way to do it. – user1705452 Oct 18 '12 at 03:43

1 Answers1

5

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.

John Estropia
  • 17,460
  • 4
  • 46
  • 50
  • ok - thanks for this - there are quite a few questions on use of NSJSONSerialization and not checking the return type (or always assuming it is not variable) is/was (for me anyway) a subtle gotcha. The purpose of this post was to confirm and clarify. – user1705452 Oct 18 '12 at 03:55