78

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.

Aizzat Suhardi
  • 753
  • 11
  • 19
Classified
  • 5,759
  • 18
  • 68
  • 99

15 Answers15

173
obj.length() == 0

is what I would do.

Scott Tesler
  • 39,441
  • 4
  • 25
  • 20
44

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.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 1
    The best answer – ParSa Jan 29 '20 at 12:20
  • It adds calculation and cpu load and not so good approach. – Hamid Araghi Jan 17 '21 at 15:36
  • 1
    @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. – Jonathan E. Landrum Feb 25 '21 at 14:56
  • in my case I had to use .equals("[]") as the object itself came as null. – Smart Coder Oct 25 '22 at 21:01
14

If empty array:

.size() == 0

if empty object:

.length() == 0
Rohan Lodhi
  • 1,385
  • 9
  • 24
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() 
Anderson
  • 1,011
  • 2
  • 11
  • 24
  • 3
    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 Oct 03 '13 at 23:02
  • @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. – Anderson Oct 03 '13 at 23:13
  • 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. http://www.json.org/javadoc/org/json/JSONObject.html. thx again for your responses and help – Classified Oct 03 '13 at 23:20
  • At the moment Jackson. But this does not mean that org.json is bad, just different. – Anderson Oct 03 '13 at 23:22
  • 1
    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. – Anderson Oct 03 '13 at 23:27
  • If the object is a Map then isEmpty() works, but one must first cast to java.util.Map. – Hot Licks Oct 03 '13 at 23:52
5

Try:

if (record.has("problemkey") && !record.isNull("problemkey")) {
    // Do something with object.
}
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • 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. – Classified Oct 03 '13 at 22:55
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

kommradHomer
  • 4,127
  • 5
  • 51
  • 68
2

I would do the following to check for an empty object

obj.similar(new JSONObject())
sorjef
  • 554
  • 5
  • 15
  • 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. – Csteele5 Dec 14 '15 at 04:35
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.

2

For this case, I do something like this:

var obj = {};

if(Object.keys(obj).length == 0){
        console.log("The obj is null")
}
rachit7
  • 131
  • 1
  • 8
0
Object getResult = obj.get("dps"); 
if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
    handleEmptyDps(); 
} 
else {
    handleResult(getResult); 
}
Hot Licks
  • 47,103
  • 17
  • 93
  • 151
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) {}
Sashko
  • 191
  • 3
  • 10
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)
Max
  • 183
  • 1
  • 5
  • 18
  • 1
    Please look at [How do I format my Code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) and then add some explanation to your answer. – Clijsters Apr 03 '17 at 14:10
0
@Test
public void emptyJsonParseTest() {
    JsonNode emptyJsonNode = new ObjectMapper().createObjectNode();
    Assert.assertTrue(emptyJsonNode.asText().isEmpty());
}
Mikey
  • 380
  • 4
  • 15
-2

Use the following code:

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

}
michaelrmcneill
  • 1,163
  • 1
  • 10
  • 23
-3

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

APerson
  • 702
  • 6
  • 10