SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullListAsEmpty,全是忽悠人的,都不验证下,只知道转载。
WriteMapNullValue只是可以让null的值显示出来,默认是过滤掉null值的
上面是加SerializerFeature参数,其他还可以加SerializeFilter参数
用法如下:
JsonObject:
public static void main(String[] args) { JSONObject dataChange = new JSONObject(); dataChange.put("column","test"); dataChange.put("oldVal",null); dataChange.put("newVal","2"); ValueFilter valueFilter = new ValueFilter() { @Override public Object process(Object object,String name,Object value) { if (value == null) return ""; return value; } }; String result = JSONObject.toJSONString(dataChange,valueFilter); System.out.print(result); }
JsonArray:
public static void main(String[] args) { List<CriticalOperInfoVo> criticalOperInfoList = new ArrayList<CriticalOperInfoVo>(); criticalOperInfoList.add(new CriticalOperInfoVo("firstname","1","2")); criticalOperInfoList.add(new CriticalOperInfoVo("lastname",null,"2")); if (criticalOperInfoList != null && criticalOperInfoList.size() > 0) { JSONArray dataChanges = new JSONArray(); for (CriticalOperInfoVo criticalOperInfo : criticalOperInfoList) { JSONObject dataChange = new JSONObject(); dataChange.put("column",criticalOperInfo.getColumn()); dataChange.put("oldVal",criticalOperInfo.getOldVal()); dataChange.put("newVal",criticalOperInfo.getNewVal()); dataChanges.add(dataChange); } ValueFilter valueFilter = new ValueFilter() { @Override public Object process(Object object,Object value) { if (value == null) return ""; return value; } }; String result = JSONArray.toJSONString(dataChanges, valueFilter); System.out.print(result); } }