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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
92Jacko
  • 523
  • 2
  • 10
  • 18

2 Answers2

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.

meda
  • 45,103
  • 14
  • 92
  • 122
Brian Roach
  • 76,169
  • 12
  • 136
  • 161
  • 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). – 92Jacko Jan 21 '12 at 17:12
  • 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. – Brian Roach Jan 21 '12 at 17:16
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));
Perception
  • 79,279
  • 19
  • 185
  • 195
kosa
  • 65,990
  • 13
  • 130
  • 167