80

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.

17 Answers 17

176
obj.length() == 0

is what I would do.

Sign up to request clarification or add additional context in comments.

Comments

46

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.

4 Comments

The best answer
It adds calculation and cpu load and not so good approach.
@HamidAraghi not really, the underlying representation is already a HashMap with String keys, so the conversion is quite speedy. The "faster" approach, if that's necessary for extremely large JSON objects, is to compare the length() as demonstrated in other answers. But this approach is hardly slow, even in that case.
in my case I had to use .equals("[]") as the object itself came as null.
14

If empty array:

.size() == 0

if empty object:

.length() == 0

Comments

6

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

6 Comments

thx for your suggestion. i'm using org.json (jar file org.json-20120521.jar). it doesn't look like there's a method called isEmptyObject. =(
@Classified I am not familiar with org.json so this might not be the optimum way. An empty object has no member so therefore method keys() should return iterator with length zero. getJSONObject("problemkey").keys() - check the length of that.
which library do you use? I found org.json via a google search so I don't know how good/bad it is but it looked fairly popular. json.org/javadoc/org/json/JSONObject.html. thx again for your responses and help
At the moment Jackson. But this does not mean that org.json is bad, just different.
Another workaround would be to convert your problem value to JSON string and compare it with string "{}". Something like obj.get("dps").toString().equals("{}"). But check what does toString actualy return regarding to whitespaces.
|
5

Try:

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

1 Comment

thx for the suggestion. when I tried your code, it thinks {} is not null and prints my message, which is not what i want. i dont' know why it thinks {} is not null.
3

For this case, I do something like this:

var obj = {};

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

1 Comment

Nice one, but this seems more like JavaScript rather than Java.
2

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

Comments

2

I would do the following to check for an empty object

obj.similar(new JSONObject())

1 Comment

This is actually pretty clever. I wouldn't use it on something so small as this, but it's definitely not an empty-check I had thought of before.
2

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.

Comments

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

Comments

0

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

Comments

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

Comments

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

1 Comment

Please look at How do I format my Code blocks? and then add some explanation to your answer.
0

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

Comments

0

Util function code:

import org.json.JSONObject;

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

call:

boolean isEmpty = isJsonEmpty(jsonObj);

Comments

-2

Use the following code:

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

}

1 Comment

How would the cast go?
-3

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

1 Comment

thx for the suggestion. I checked and there are no extra spaces. =(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.