遵循的步骤:
- 将JSON字符串转换为
Map<String,Object>
使用Gson#fromJson() - 迭代地图并从地图中删除为
null
或为空的条目ArrayList
。 - 使用Gson#toJson()从最终映射中形成JSON String 。
注意:
使用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);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);输出;
{ "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 }


