简体   繁体   中英

Objective-C JSON types

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?

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM