How to check if JSON object is empty in Java?

92Jacko picture 92Jacko · Jan 21, 2012 · Viewed 34.9k times · Source

In Java, if I use the following JSON string as an example, how would I check if the objects are empty/null?

{"null_object_1" : [], "null_object_2" : [null] }

I have tried using:

if(!jsonSource.isNull("null_object_1"))  {/*null_object_1 is not empty/null*/}
if(!jsonSource.isNull("null_object_2"))  {/*null_object_2 is not empty/null*/}

But these IF statements still return true (as if they are not empty/null).

Does anyone have a solution?

Edit: By "object", I actually meant array.

Answer

Brian Roach picture Brian Roach · Jan 21, 2012

Neither of those two things are null; they are arrays. The result is exactly what you would expect.

One of your arrays is empty, the other contains a single element that is null.

If you want to know if an array is empty, you would need to get the array, then check its length.

JSONObject myJsonObject = 
    new JSONObject("{\"null_object_1\":[],\"null_object_2\":[null]}");

if (myJsonObject.getJSONArray("null_object_1").length() == 0) {
    ... 
}

Edit to clarify: An array having no elements (empty) and an array that has an element that is null are completely different things. In the case of your second array it is neither null nor empty. As I mentioned it is an array that has a single element which is null. If you are interesting in determining if that is the case, you would need to get the array then iterate through it testing each element to see if it were null and acting upon the results accordingly.