How to test if JSON Collection object is empty in Java

JavaJson

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

obj.length() == 0

is what I would do.

Solution 2 - Java

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 - Java

If empty array:

.size() == 0

if empty object:

.length() == 0

Solution 4 - Java

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() 

Solution 5 - Java

Try:

if (record.has("problemkey") && !record.isNull("problemkey")) {
    // Do something with object.
}

Solution 6 - Java

I have added isEmpty() methods on JSONObject and JSONArray()

 //on JSONObject 
 public Boolean isEmpty(){         
     return !this.keys().hasNext();
 }

...

//on JSONArray
public Boolean isEmpty(){
    return this.length()==0;        
}

you can get it here https://github.com/kommradHomer/JSON-java

Solution 7 - Java

I would do the following to check for an empty object

obj.similar(new JSONObject())

Solution 8 - Java

if you want to check for the json empty case, we can directly use below code

String jsonString = {};
JSONObject jsonObject = new JSONObject(jsonString);
if(jsonObject.isEmpty()){
 System.out.println("json is empty");
} else{
 System.out.println("json is not empty");
}

this may help you.

Solution 9 - Java

For this case, I do something like this:

var obj = {};

if(Object.keys(obj).length == 0){
        console.log("The obj is null")
}

Solution 10 - Java

Object getResult = obj.get("dps"); 
if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
    handleEmptyDps(); 
} 
else {
    handleResult(getResult); 
}

Solution 11 - Java

If JSON returned with following structure when records is an ArrayNode:

{}client 
  records[]

and you want to check if records node has something in it then you can do it using a method size();

if (recordNodes.get(i).size() != 0) {}

Solution 12 - Java

if (jsonObj != null && jsonObj.length > 0)

To check if a nested JSON object is empty within a JSONObject:

if (!jsonObject.isNull("key") && jsonObject.getJSONObject("key").length() > 0)

Solution 13 - Java

@Test
public void emptyJsonParseTest() {
    JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
    Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}

Solution 14 - Java

Use the following code:

if(json.isNull()!= null){  //returns true only if json is not null

}

Solution 15 - Java

Try /*string with {}*/ string.trim().equalsIgnoreCase("{}")), maybe there is some extra spaces or something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClassifiedView Question on Stackoverflow
Solution 1 - JavaScott TeslerView Answer on Stackoverflow
Solution 2 - JavadjechlinView Answer on Stackoverflow
Solution 3 - JavaRohan LodhiView Answer on Stackoverflow
Solution 4 - JavaAndersonView Answer on Stackoverflow
Solution 5 - JavaOrel ErakiView Answer on Stackoverflow
Solution 6 - JavakommradHomerView Answer on Stackoverflow
Solution 7 - JavasorjefView Answer on Stackoverflow
Solution 8 - JavaVenkata Naresh BabuView Answer on Stackoverflow
Solution 9 - Javarachit7View Answer on Stackoverflow
Solution 10 - JavaHot LicksView Answer on Stackoverflow
Solution 11 - JavaSashkoView Answer on Stackoverflow
Solution 12 - JavaBharathi RajaView Answer on Stackoverflow
Solution 13 - JavaMikeyView Answer on Stackoverflow
Solution 14 - Javauser3487921View Answer on Stackoverflow
Solution 15 - JavaAPersonView Answer on Stackoverflow