How to check "isEmpty ()" in a Gson JsonObject?

I used the Google Gson API to create JSON. When I initialized JsonObject with:

JsonObject json = new JsonObject(); 

and print it out, it was actually {} .

I tried to exclude the "empty" JSON, i.e. tags {} that have not added any properties. But I could not find a method similar to isEmpty() in the Gson API.

How can I find out "empty" JSON with the Gson API?

+5
source share
2 answers

You can use JsonObject#entrySet() , then check its size() .

 JsonObject jsonObject = ...; if (jsonObject.entrySet().size() == 0) { // or isEmpty() // do something } 
+10
source

It is more correct to use Set.isEmpty () for this purpose.

 if (jsonObject.entrySet().isEmpty()) { } 
+5
source

Source: https://habr.com/ru/post/1237898/


All Articles