Craig
Craig

Reputation: 233

Cocoa JSON - Check whether array or dictionary

I am using the Cocoa JSON framework ( http://code.google.com/p/json-framework/ ) to communicate with an API.

The problem is that the API returns a dictionary if there is an error but returns an array of the results if it works.

Is there a good way to detect if the JSONValue is an array or a dictionary?

Thanks.

Upvotes: 3

Views: 1612

Answers (3)

Rajesh Loganathan
Rajesh Loganathan

Reputation: 11247

Try this:

if ([YourData isKindOfClass:[NSArray class]])
{
    NSLog(@"Array format found");
}
else
{
    NSLog(@"Dictionary format found");
}

Upvotes: 0

Peter Hosey
Peter Hosey

Reputation: 96373

You can use isKindOfClass: to test whether the object is an instance of NSDictionary or of any subclass thereof.

In most circumstances, you would be better served by a respondsToSelector: check, but this is one case where you really are better off testing its class membership.

Of course, you can test whether it's an array instead of whether it's a dictionary; as long as the API you're using only returns an array or dictionary, the effect is the same.

For true robustness, test both array and dictionary membership, and throw an exception or present an error if the object is neither.

Upvotes: 6

Danil
Danil

Reputation: 1893

Maybe try to check length property.

if (jsonObj.length) {
   //doSomeWork
}

Upvotes: 0

Related Questions