Determine whether JSON is a JSONObject or JSONArray

93,850

Solution 1

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()

Solution 2

There are a couple ways you can do this:

  1. 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 a JSONObject, if it is a [, you are dealing with a JSONArray.
  2. If you are dealing with JSON (an Object), then you can do an instanceof check. yourObject instanceof JSONObject. This will return true if yourObject is a JSONObject. The same applies to JSONArray.

Solution 3

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
}

Solution 4

Presenting an another way :

if(server_response.trim().charAt(0) == '[') {
    Log.e("Response is : " , "JSONArray");
} else if(server_response.trim().charAt(0) == '{') {
    Log.e("Response is : " , "JSONObject");
}

Here server_response is a response String coming from server

Solution 5

A more fundamental way of doing this is the following.

JsonArray is inherently a List

JsonObject is inherently a Map

if (object instanceof Map){
    JSONObject jsonObject = new JSONObject();
    jsonObject.putAll((Map)object);
    ...
    ...
}
else if (object instanceof List){
    JSONArray jsonArray = new JSONArray();
    jsonArray.addAll((List)object);
    ...
    ...
}
Share:
93,850
Greg
Author by

Greg

FP |> I <3

Updated on November 01, 2021

Comments

  • Greg
    Greg over 2 years

    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?

  • Greg
    Greg almost 13 years
    That definitely worked. In the end though, I put the string into a JSONObject and if it threw an error, then I knew it was a JSONArray. try { return new JSONObject(json); } catch (Exception e) { } try { return new JSONArray(json); } catch (Exception e) { }
  • gamerson
    gamerson over 11 years
    I think the question assumes that you will be working with a plain string so using the instanceof or getClass().getName() wont work.
  • Hot Licks
    Hot Licks over 11 years
    @gamerson -- That's odd -- it's worked for me many times. You just have to have the parser return either object, vs specifying which.
  • Shreyash Mahajan
    Shreyash Mahajan over 11 years
    nice job. hope it will check for both JsonObject and Json Array
  • Hot Licks
    Hot Licks about 10 years
    Clearly folks don't understand this. Pretty much every parser I've seen has a parse option to return a "JSONInstance" or simply "Object", or whatever. Parse the JSON and then ask it what it is. A parser which doesn't have this ability is broken.
  • Hot Licks
    Hot Licks about 10 years
    (This is, in fact, Neworld's answer, more or less.)
  • Marbal
    Marbal over 9 years
    Your first option won't work reliably, because whitespace is allowed at the start of JSON data. You need to skip any leading whitespace and check the first non-whitespace character.
  • nicholas.hauschild
    nicholas.hauschild over 9 years
    @user9876 Thanks for the heads up. Edited to reflect your comment.
  • P-RAD
    P-RAD over 8 years
    @neworld but what if I am in the middle of a loop. trying to get a data.getJSONArray() or data.getJSONObject() will potentially throw a JSONEXception!!
  • Christophe Roussy
    Christophe Roussy over 8 years
    Not Android specific and I like this version best because it uses no character checks, but the json.has("data") supposes the whole thing is optional (not asked for).
  • amit pandya
    amit pandya over 6 years
    Hi my objectdata is middle of response so how can i detect that? to check whether its a JSONObject or JSONArray??? and In your answer String data = "{ ... }"; is having value of whole response???
  • neworld
    neworld over 6 years
    To accomplish that, you have to parse your JSON using JSONTokener. I didn't do that, but I suppose you should skipPast("your_key"). But I am not sure. However, you should consider using json mapper: Gson, Jackson, Moshi and ton of others.