首页 > 代码库 > fastJosn 转换对象为json格式字符串时, 空字段处理.

fastJosn 转换对象为json格式字符串时, 空字段处理.

    public static void main(String[] s) {
        CybWmsCommoditiesVo cybWmsCommoditiesVo = new CybWmsCommoditiesVo();
        CybItemVo cybItemVo = new CybItemVo();
        cybItemVo.setStockUnit("2134");
        cybWmsCommoditiesVo.setSupplierCode("24234");
        cybWmsCommoditiesVo.setItem(cybItemVo);
        
        String requestBody = JSON.toJSONString(cybWmsCommoditiesVo, filter);
        System.out.print(requestBody);
    }

private static ValueFilter filter = new ValueFilter() {
@Override
public Object process(Object obj, String s, Object v) {
if (v == null)
return "";
return v;
}
};
 

JSON.toJSONString()方法默认会将对象中的空字符串忽略.

加上这个过滤器后,所有的null值和""值都会被转换成""值输出到字符串中.

fastJosn 转换对象为json格式字符串时, 空字段处理.