Remove empty collections from a JSON with Gson

collections, gson, java, javascript, json

Solution

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
  }

Problem

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 Gson gson = new Gson(); String json = gson.toJson(periodo); ``` I print json and I have this: ``` {"idPeriodo":121,"codigo":"2014II", "activo":false,"tipoPeriodo":1, "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,"aiAvisos":[], "aiAlumnoCarreraConvalidacionCursos":[], "aiAlumnoMatriculas":[],"aiMallaCurriculars":[], "aiAlumnoCarreraEstados":[],"aiAdmisionGrupos":[], "aiMatriculaCronogramaCabeceras":[], "aiAlumnoCarreraConvalidacions":[], "aiHorarioHorases":[],"aiAsistencias":[], "aiAlumnoPreMatriculas":[], "aiAlumnoMatriculaCursoNotaDetalles":[], "aiOfertaAcademicas":[],"aiTarifarios":[]} ``` For example for that json I don't want to have the collection aiAvisos, there is a way to delete this from the json. I'm working with a lot of collections actually here I show one, I really need remove these from the json. I need something like this: ``` {"idPeriodo":121,"codigo":"2014II", "activo":false,"tipoPeriodo":1, "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} ``` I tried setting the collections to null, I check the documentation and there's no method there neither... Please any suggestions. Thanks a lot who read this!

Original source

Related problems