Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if JSON object is empty in Java?

Tags:

java

json

isnull

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.

like image 767
92Jacko Avatar asked Jan 21 '12 16:01

92Jacko


1 Answers

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.

like image 189
Brian Roach Avatar answered Sep 28 '22 06:09

Brian Roach