17

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,476
  • 7
  • 31
  • 51

2 Answers2

20

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
  • 274,122
  • 60
  • 696
  • 724
17

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

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

}
UDJ
  • 281
  • 2
  • 10