How to test if JSON object is empty in Java


The JSON 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.

This question is tagged with java json

~ Asked on 2013-10-03 22:36:01

The Best Answer is


obj.length() == 0

is what I would do.

~ Answered on 2014-06-09 21:18:09


If you're okay with a hack -


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.

~ Answered on 2013-10-04 00:04:27

Most Viewed Questions: