15

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

JsonObject json = new JsonObject();

and print it out, it was in fact {}.

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

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

Zelong
  • 2,356
  • 7
  • 29
  • 50

2 Answers2

19

You can use JsonObject#entrySet() to get the JSON object's set of name/value pairs (its members). That returns a Set which has the traditional isEmpty() method you're looking for.

For example,

JsonObject jsonObject = ...;
Set<Map.Entry<String,JsonElement>> members = jsonObject.entrySet();
if (members.isEmpty()) {
    // do something
}
Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
14

Its more correct to use the Set.isEmpty() for this purpose

if (jsonObject.entrySet().isEmpty()) {

}
UDJ
  • 241
  • 2
  • 10