开发者

Cocoa JSON - Check whether array or dictionary

开发者 https://www.devze.com 2022-12-08 04:32 出处:网络
I am using the Cocoa JSON framework ( http://code.google.com/p/json-framework/ ) to commu开发者_开发问答nicate with an API.

I am using the Cocoa JSON framework ( http://code.google.com/p/json-framework/ ) to commu开发者_开发问答nicate 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.


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.


Maybe try to check length property.

if (jsonObj.length) {
   //doSomeWork
}


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消