使用Gson从JSON中删除空集合 [英] Remove empty collections from a JSON with Gson

查看:311
本文介绍了使用Gson从JSON中删除空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用gson删除具有空集合或空值的属性。

  Aiperiodo periodo = periodoService(); 
// periodo来自具有很多值的服务方法
Gson gson = new Gson();
String json = gson.toJson(periodo);

我打印json,我有:

  {idPeriodo:121,codigo:2014II,
activo:false,tipoPeriodo:1,
fechaInicioPreMatricula: 2014年1月3日,
fechaFinPreMatricula:2014年7月1日,
fechaInicioMatricula:2014年7月15日,
fechaFinMatricula: ,
fechaInicioClase:2014年9月9日,
fechaFinClase:dic 14,2014,
fechaActa:ene 15,2015 bfechaUltModificacion:2014年5月28日12:28:26 PM,
usuarioModificacion:1,aiAvisos:[],
aiAlumnoCarreraConvalidacionCursos:[],
aiAlumnoMatriculas:[],aiMallaCurriculars:[],
aiAlumnoCarreraEstados:[],aiAdmisionGrupos:[],
aiMatriculaCronogramaCabeceras :[],
aiHorarioHorases:[],aiAsistencias:[],
aiAlumnoPreMatriculas:[],
aiAlumnoMatriculaCursoNotaDetalles:[],
aiOfertaAcademicas :[],aiTarifarios:[]}

想要有集合aiAvisos,有一种方法从json中删除这个。
我正在使用很多集合,在这里我显示一个,我真的需要从json中删除这些。



我需要这样: / p>

  {idPeriodo:121,codigo:2014II,
activo:false,tipoPeriodo :1,
fechaInicioPreMatricula:2014年1月1日,
fechaFinPreMatricula:2014年第1季度,
fechaInicioMatricula:2014年jul 15, b $ bfechaFinMatricula:2014年3月3日,
fechaInicioClase:2014年9月9日,
fechaFinClase:dic 14,2014,
fechaActa :ene 15,2015,
fechaUltModificacion:2014年5月28日12:28:26 PM,
usuarioModificacion:1}



我试图将集合设置为null,我检查文档,没有没有方法... ...



请提供任何建议。



非常感谢您阅读这篇文章!

解决方案

以下步骤:





=http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html#setPrettyPrinting%28%29 =nofollow> GsonBuilder#setPrettyPrinting( ),它配置Gson输出适合页面的Json,用于漂亮的打印。



示例代码:

  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);

(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() == 0){
it.remove();
}
}
}

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

输出;

 code> {
idPeriodo:121.0,
codigo:2014II,
activo:false,
tipoPeriodo:1.0,
fechaInicioPreMatricula:2014年1月1日,
fechaFinPreMatricula:2014年第1季度,
fechaInicioMatricula:2014年第15期,
fechaFinMatricula :bing,bbbbfechaFinClase:dic 14,2014,
fechaActa:ene 15, 2015,
fechaUltModificacion:2014年5月28日12:28:26 PM,
usuarioModificacion:1.0
}


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!

解决方案

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.

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();
        }
    }
}

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
  }

这篇关于使用Gson从JSON中删除空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆