fastJson的null值转空串""

前端之家收集整理的这篇文章主要介绍了fastJson的null值转空串""前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
网上说的什么加

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

猜你在找的Json相关文章