Search code examples
javajson-simple

checking if a string that is a array of JSONObject is empty


So I am receiving, a jsonobject from an api call.

inside the jsonobject there is a field that can hold an array of JSONObjects

for example

{ "order":[]}

how can I check if the array is empty or not?

JSONSimple library

JSONObject[] check = new JSONObject[0];

JSONObject g = new JSONObject();
g.put("test", check);

System.out.println(((List<JSONObject>)g.get("test")).size());

Actual result: error

Desired result: size of json[]

Thanks


Solution

  • You cannot cast an array of JsonObject (JSONObject[]) to a List of JSONObject (List) - they are 2 different class with 2 different heirarchy. Cast it to JSONObject[], and since now it is an array and not a list, use length, not size().

        JSONObject[] check = new JSONObject[0];
    
        JSONObject g = new JSONObject();
        g.put("test", check);
    
        //System.out.println(((List<JSONObject>) g.get("test")).size());
        System.out.println(((JSONObject[]) g.get("test")).length);