Fastjson 处理空字段

淺唱寂寞╮ 提交于 2019-12-04 23:06:30

Fastjson的SerializerFeature序列化属性

  • QuoteFieldNames———-输出key时是否使用双引号,默认为true 

  • WriteMapNullValue——–是否输出值为null的字段,默认为false 

  • WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null 

  • WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null 

  • WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null 

  • WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null

 Fastjson实际处理方式

1.@JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue})

fastJson默认是不输出value为null的字段,如果在该字段上加上这个注解,则会输出

2.加过滤器,可以让value为null的字段都输出空字符串

public class User {

    private String name;

    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
   public static void main(String[] args) {
        User user = new User();
        user.setName("curry");

        ValueFilter filter = (Object object, String name, Object v) -> {
            if (v==null) {
                return "";
            }
            return v;
        };
        System.out.println(JSON.toJSONString(user, filter));
    }

输出:

{"age":"","name":"curry"}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!