Determine whether JSON is a JSONObject or JSONArray

Greg picture Greg · May 25, 2011 · Viewed 87.5k times · Source

I am going to receive either a JSON Object or Array from server, but I have no idea which it will be. I need to work with the JSON, but to do so, I need to know if it is an Object or an Array.

I am working with Android.

Does any one have a good way of doing this?

Answer

neworld picture neworld · Oct 27, 2012

I found better way to determine:

String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
  //you have an object
else 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()