Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

gson

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?

like image 241
Zelong Avatar asked Dec 11 '15 03:12

Zelong


People also ask

How do I check if a JSONArray is empty?

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.

How do I use JSONArray?

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.

How do you check a JSON object is empty or not?

return Object.keys(obj).length === 0; This is typically the easiest way to determine if an object is empty.


2 Answers

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
}
like image 107
Sotirios Delimanolis Avatar answered Oct 14 '22 19:10

Sotirios Delimanolis


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

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

}
like image 36
UDJ Avatar answered Oct 14 '22 18:10

UDJ