Classified Classified - 7 days ago 5
Java Question

How to test if JSON object is empty in Java

I'm new to working with JSON objects so hopefully someone can guide me to the solution. My JSON object I'm receiving looks like this:

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


What I'm trying to test for is "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 but to no avail.

Here's my code snippet. I can add more code if needed but this is what I've tried thus far and I haven't been successful.

// 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("crap");
}


I expected one of these lines to print "crap" out since {"dps":{}} but for whatever reason, it's not. Thanks for any help you can give me.

EDIT: I'm using org.json. the jar file is org.json-20120521.jar

Answer
obj.length() == 0

is what I would do.