Remove empty collections from a JSON with Gson

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 or Map.
  • 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.

Sample code:

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
...  
 
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Map<String, Object> data = new Gson().fromJson(jsonString, type);

for (Iterator<Map.Entry<String, Object>> it = data.entrySet().iterator(); it.hasNext();) {
    Map.Entry<String, Object> entry = it.next();
    if (entry.getValue() == null) {
        it.remove();
    } else if (entry.getValue().getClass().equals(ArrayList.class)) {
        if (((ArrayList<?>) entry.getValue()).size() == 0) {
            it.remove();
        }
    } else if (entry.getValue() instanceof Map){ //removes empty json objects {}
        Map<?, ?> m = (Map<?, ?>)entry.getValue();
        if(m.isEmpty()) {
           it.remove();
        }
    }
}

String json = new GsonBuilder().setPrettyPrinting().create().toJson(data);
System.out.println(json);

output;

  {
    "idPeriodo": 121.0,
    "codigo": "2014II",
    "activo": false,
    "tipoPeriodo": 1.0,
    "fechaInicioPreMatricula": "may 1, 2014",
    "fechaFinPreMatricula": "jul 1, 2014",
    "fechaInicioMatricula": "jul 15, 2014",
    "fechaFinMatricula": "ago 3, 2014",
    "fechaInicioClase": "ago 9, 2014",
    "fechaFinClase": "dic 14, 2014",
    "fechaActa": "ene 15, 2015",
    "fechaUltModificacion": "May 28, 2014 12:28:26 PM",
    "usuarioModificacion": 1.0
  }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)