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

问题描述

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

Aiperiodo periodo = periodoService();
//periodo comes from a service method with a lot of values
Gson gson = new Gson();
String json = gson.toJson(periodo);

我打印 json 并且我有这个:

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":[]}

例如,对于那个 json,我不想拥有 aiAvisos 集合,有一种方法可以从 json 中删除它.我实际上正在处理很多集合,我在这里展示了一个,我真的需要从 json 中删除这些.

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.

我需要这样的东西:

{"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...

请提出任何建议.

非常感谢阅读本文的人!

Thanks a lot who read this!

推荐答案

要遵循的步骤:

  • 使用
  • 迭代地图并从地图中删除null或空ArrayListMap的条目.
  • 使用 Gson#toJson().
  • 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().
    • 注意: 使用 GsonBuilder#setPrettyPrinting() 配置 Gson 以输出适合页面的 Json 以进行漂亮的打印.

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

      示例代码:

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

      输出;

        {
          "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 中删除空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 11:23