Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if JSON Collection object is empty in Java

Tags:

java

json

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.

like image 453
Classified Avatar asked Oct 03 '13 22:10

Classified


People also ask

How can we check if a JSON object is empty or not in Java?

return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.

How check if JSON is empty?

If you want to check if your response is not empty try : if ( json. length == 0 ) { console. log("NO DATA!") }

Can a JSON object be empty?

JSON data has the concept of null and empty arrays and objects. This section explains how each of these concepts is mapped to the data object concepts of null and unset.

How do I check if a JSON object is empty in node?

Object. keys(myObj). length === 0; As there is need to just check if Object is empty it will be better to directly call a native method Object.


3 Answers

obj.length() == 0

is what I would do.

like image 119
Scott Tesler Avatar answered Oct 08 '22 17:10

Scott Tesler


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.

like image 44
djechlin Avatar answered Oct 08 '22 17:10

djechlin


If empty array:

.size() == 0

if empty object:

.length() == 0
like image 13
Rohan Lodhi Avatar answered Oct 08 '22 19:10

Rohan Lodhi