Question

I'm using NSJSONSerialization JSONObjectWithData:options:error: in an iOS 5 project to read a JSON string and convert it to a Foundation object. Is there an easy way to find out if the object or some of its children are arrays, dictionaries, numbers or strings?

Was it helpful?

Solution

You can check to see if the returned object is a certain class with the -isKindOfClass: method. For example, to check if it's an array:

id jsonObj = [NSJSONSerialization JSONObjectWithData:...]
if ([jsonObj isKindOfClass:[NSArray class]] {
    // Do array stuff...
}

Similarly for the other foundation types.

OTHER TIPS

Please be careful about using NSJSONSerialization since it is only supported on iOS 5.0+ and Mac OS X 10.7+.

I think you can also have a try with third-party libraries, such as:

  • JSONKit (faster than NSJSONSerialization per its introduction)
  • SBJson

Both are easy to use and flexible.

All objects can answer their class. Even more useful, you can ask if something is a member of a class or any of it's subclasses:

id jsonParse;

if ([jsonParse isKindOfClass:[NSArray self]]) {
    for (id element in (NSArray *)jsonParse) {

        // and so on
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top