8

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 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for clarifying Java's null (: I'm too used to working with PHP (where checking for null usually goes for both empty and null).
Glad I could help. Honestly, IMHO I would avoid using null for this reason. In Java null has a special meaning that does not equate to 0 or "empty" - it can only be assigned to object reference variables and indicates that the variable has no object reference assigned to it.
2

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.