Classified
Classified

Reputation: 6060

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.

Upvotes: 80

Views: 252807

Answers (17)

crifan
crifan

Reputation: 14328

Util function code:

import org.json.JSONObject;

    public static boolean isJsonEmpty(JSONObject curJson){
        return (null != curJson) && (0 == curJson.length());
    }

call:

boolean isEmpty = isJsonEmpty(jsonObj);

Upvotes: 0

guymac
guymac

Reputation: 406

javax.json.JsonObject extends Map, so you can use the isEmpty() method of Map.

JsonObject dps = obj.getJsonObject("dps");
if (dps != null && !dps.isEmpty())) ... else ...

Upvotes: 0

Bharathi Raja
Bharathi Raja

Reputation: 11

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)

Upvotes: 0

rachit7
rachit7

Reputation: 141

For this case, I do something like this:

var obj = {};

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

Upvotes: 3

Venkata Naresh Babu
Venkata Naresh Babu

Reputation: 367

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.

Upvotes: 2

Rohan Lodhi
Rohan Lodhi

Reputation: 1395

If empty array:

.size() == 0

if empty object:

.length() == 0

Upvotes: 14

djechlin
djechlin

Reputation: 60788

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.

Upvotes: 46

Mikey
Mikey

Reputation: 430

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

Upvotes: 0

Sashko
Sashko

Reputation: 191

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) {}

Upvotes: 0

sorjef
sorjef

Reputation: 574

I would do the following to check for an empty object

obj.similar(new JSONObject())

Upvotes: 2

kommradHomer
kommradHomer

Reputation: 4212

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

Upvotes: 2

user3487921
user3487921

Reputation: 39

Use the following code:

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

}

Upvotes: -2

Scott Tesler
Scott Tesler

Reputation: 39778

obj.length() == 0

is what I would do.

Upvotes: 176

Hot Licks
Hot Licks

Reputation: 47729

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

Upvotes: 0

Anderson
Anderson

Reputation: 1011

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

Upvotes: 6

APerson
APerson

Reputation: 712

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

Upvotes: -3

Orel Eraki
Orel Eraki

Reputation: 12196

Try:

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

Upvotes: 5

Related Questions