How to check if JSON object is empty in Java?

41k Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

As per this documentation JSONObject API, isNull checks for value NULL, which is not true in your case.

If 'null_object_1' value is String, you need to use String temp = getString("keyName") and check

!("".equals(temp));