Json – Cocoa JSON – Check whether array or dictionary

cocoajson

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.

Best Answer

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.