How to test if JSON Collection object is empty in Java

The JSON Collection object I'm receiving looks like this:

[{"foo1":"bar1", "foo2":"bar2", "problemkey": "problemvalue"}]

What I'm trying to test for is the existence of problemvalue. If problemvalue returns a JSON Object, I'm happy. If it doesn't, it will return as {}. How do I test for this condition? I've tried several things to no avail.

This is what I've tried thus far:

//      if (obj.get("dps") == null) {  //didn't work
//      if (obj.get("dps").equals("{}")) {  //didn't work
if (obj.isNull("dps")) {  //didn't work
    System.out.println("No dps key");
}

I expected one of these lines to print "No dps key" because {"dps":{}}, but for whatever reason, it's not. I'm using org.json. The jar file is org.json-20120521.jar.


Solution 1:

obj.length() == 0

is what I would do.

Solution 2:

If you're okay with a hack -

obj.toString().equals("{}");

Serializing the object is expensive and moreso for large objects, but it's good to understand that JSON is transparent as a string, and therefore looking at the string representation is something you can always do to solve a problem.

Solution 3:

If empty array:

.size() == 0

if empty object:

.length() == 0

Solution 4:

A JSON notation {} represents an empty object, meaning an object without members. This is not the same as null. Neither it is string as you are trying to compare it with string "{}". I don't know which json library are you using, but try to look for method something like:

isEmptyObject()