Reputation: 2556
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?
Upvotes: 17
Views: 16022
Reputation: 280011
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
}
Upvotes: 21
Reputation: 301
Its more correct to use the Set.isEmpty() for this purpose
if (jsonObject.entrySet().isEmpty()) {
}
Upvotes: 18