Objective-C JSON types
-
05-06-2021 - |
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?
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
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