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?
You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not.
jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
return Object.keys(obj).length === 0; This is typically the easiest way to determine if an object is empty.
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
}
Its more correct to use the Set.isEmpty() for this purpose
if (jsonObject.entrySet().isEmpty()) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With