Springboot使用jackson或fastjson时不过滤null值

FastJson不过滤null值

1.局部

在属性上加上注解

    @JSONField(serialzeFeatures= {SerializerFeature.WriteMapNullValue})

2.全局

实现WebMvcConfigurer

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //创建fastJson消息转换器
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        MediaType mediaTypeJson = MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE);
        supportedMediaTypes.add(mediaTypeJson);
        converter.setSupportedMediaTypes(supportedMediaTypes);
      //创建配置类
        FastJsonConfig config = new FastJsonConfig();
        config.getSerializeConfig().put(Json.class, new SwaggerJsonSerializer());

        //修改配置返回内容的过滤
        //WriteNullListAsEmpty  :List字段如果为null,输出为[],而非null
        //WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
        //DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
        //WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
        //WriteMapNullValue:是否输出值为null的字段,默认为false
        config.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect
        /*,SerializerFeature.WriteMapNullValue*/);
        converter.setFastJsonConfig(config);
        //将fastjson添加到视图消息转换器列表内
        converters.add(converter);
    }

}

SerializerFeature属性

名称 含义 备注
QuoteFieldNames 输出key时是否使用双引号,默认为true  
UseSingleQuotes 使用单引号而不是双引号,默认为false  
WriteMapNullValue 是否输出值为null的字段,默认为false  
WriteEnumUsingToString Enum输出name()或者original,默认为false  
UseISO8601DateFormat Date使用ISO8601格式输出,默认为false  
WriteNullListAsEmpty List字段如果为null,输出为[],而非null  
WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null  
WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null  
WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null  
SkipTransientField 如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true  
SortField 按字段名称排序后输出。默认为false  
WriteTabAsSpecial 把\t做转义输出,默认为false 不推荐
PrettyFormat 结果是否格式化,默认为false  
WriteClassName 序列化时写入类型信息,默认为false。反序列化是需用到  
DisableCircularReferenceDetect 消除对同一对象循环引用的问题,默认为false  
WriteSlashAsSpecial 对斜杠’/’进行转义  
BrowserCompatible 将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false  
WriteDateUseDateFormat 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);  
DisableCheckSpecialChar 一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false  
NotWriteRootClassName 含义  
BeanToArray 将对象转为array输出  
WriteNonStringKeyAsString 含义  
NotWriteDefaultValue 含义  
BrowserSecure 含义  
IgnoreNonFieldGetter 含义  
WriteEnumUsingName 含义

jackson可参考:https://blog.csdn.net/weixin_41753364/article/details/106590126

猜你喜欢

转载自blog.csdn.net/qq_45441466/article/details/110393204