Determine whether JSON is a JSONObject or JSONArray
I found better way to determine:
String data = "{ ... }";Object json = new JSONTokener(data).nextValue();if (json instanceof JSONObject) //you have an objectelse if (json instanceof JSONArray) //you have an array
tokenizer is able to return more types: http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()
There are a couple ways you can do this:
- You can check the character at the first position of the String (after trimming away whitespace, as it is allowed in valid JSON). If it is a
{
, you are dealing with aJSONObject
, if it is a[
, you are dealing with aJSONArray
. - If you are dealing with JSON (an
Object
), then you can do aninstanceof
check.yourObject instanceof JSONObject
. This will return true if yourObject is a JSONObject. The same applies to JSONArray.
This is the simple solution I'm using on Android:
JSONObject json = new JSONObject(jsonString);if (json.has("data")) { JSONObject dataObject = json.optJSONObject("data"); if (dataObject != null) { //Do things with object. } else { JSONArray array = json.optJSONArray("data"); //Do things with array }} else { // Do nothing or throw exception if "data" is a mandatory field}