Skip to content Skip to sidebar Skip to footer

Remove Null Atributes From Json With Gson

I want to remove attributes that have empty collections or null values using gson. Aiperiodo periodo = periodoService(); //periodo comes from a service method with a lot of values

Solution 1:

Steps to follow:

  • Convert the JSON String into Map<String,Object> using Gson#fromJson()
  • Iterate the map and remove the entry from the map which are null or empty ArrayList.
  • Form the JSON String back from the final map using Gson#toJson().

Note : Use GsonBuilder#setPrettyPrinting() that configures Gson to output Json that fits in a page for pretty printing.

Find the sample code here Remove empty collections from a JSON with Gson

Post a Comment for "Remove Null Atributes From Json With Gson"