Remove empty collections from a JSON with Gson

后端 未结 3 1453
滥情空心
滥情空心 2020-11-30 11:51

I want to remove attributes that have empty collections or null values using gson.

Aiperiodo periodo = periodoService();
//periodo comes fro         


        
3条回答
  •  借酒劲吻你
    2020-11-30 12:37

    Steps to follow:

    • Convert the JSON String into Map 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>() {}.getType();
    Map data = new Gson().fromJson(jsonString, type);
    
    for (Iterator> it = data.entrySet().iterator(); it.hasNext();) {
        Map.Entry 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
      }
    

提交回复
热议问题