Remove null attributes 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 Gson gson = new Gson(); String json = gson.toJson(periodo); 

I am printing 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 this json, I do not want to have aiAvisos collection, there is a way to remove this from json. I work with many collections, in fact here I am showing one, I really need to remove them from 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 is no method there ...

Please any suggestions. Yes, I am updating json which I posted a few minutes ago.

Thanks for reading this!

0
source share
1 answer

Stages:

  • Convert JSON string to Map<String,Object> using Gson # fromJson ()
  • Iterate the map and delete the entry from the null map or an empty ArrayList .
  • Form the JSON string back from the final map using Gson # toJson () .

Note. Use GsonBuilder # setPrettyPrinting () , which configures Gson to output Json, which fits on the page for a nice print.

Find sample code here Remove empty collections from JSON using Gson

+1
source

All Articles