How to check whether the given object is object or Array in JSON string

I was also having the same problem. Though, I've fixed in an easy way.

My json was like below:

[{"id":5,"excerpt":"excerpt here"}, {"id":6,"excerpt":"another excerpt"}]

Sometimes, I got response like:

{"id":7, "excerpt":"excerpt here"}

I was also getting error like you. First I had to be sure if it's JSONObject or JSONArray.

JSON arrays are covered by [] and objects are with {}

So, I've added this code

if (response.startsWith("[")) {
  //JSON Array
} else {
  //JSON Object 
}

That worked for me and I wish it'll be also helpful for you because it's just an easy method

See more about String.startsWith here - https://www.w3schools.com/java/ref_string_startswith.asp


The below sample code using jackson api can be used to always get the json string as a java list. Works both with array json string and single object json string.

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonDataHandler {
    public List<MyBeanClass> createJsonObjectList(String jsonString) throws JsonMappingException, JsonProcessingException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        List<MyBeanClass> jsonObjectList = objMapper.readValue(jsonString, new TypeReference<List<MyBeanClass>>(){});
        return jsonObjectList;
    }
}

Quite a few ways.

This one is less recommended if you are concerned with system resource issues / misuse of using Java exceptions to determine an array or object.

try{
 // codes to get JSON object
} catch (JSONException e){
 // codes to get JSON array
}

Or

This is recommended.

if (json instanceof Array) {
    // get JSON array
} else {
    // get JSON object
}

JSON objects and arrays are instances of JSONObject and JSONArray, respectively. Add to that the fact that JSONObject has a get method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions, and there ya go.

if (!json.isNull("URL"))
{
    // Note, not `getJSONArray` or any of that.
    // This will give us whatever's at "URL", regardless of its type.
    Object item = json.get("URL"); 

    // `instanceof` tells us whether the object can be cast to a specific type
    if (item instanceof JSONArray)
    {
        // it's an array
        JSONArray urlArray = (JSONArray) item;
        // do all kinds of JSONArray'ish things with urlArray
    }
    else
    {
        // if you know it's either an array or an object, then it's an object
        JSONObject urlObject = (JSONObject) item;
        // do objecty stuff with urlObject
    }
}
else
{
    // URL is null/undefined
    // oh noes
}

Tags:

Java

Json

Getjson