Springboot使⽤jackson或fastjson时过滤null值Springboot使⽤jackson或fastjson时过滤null值
Jackson全局过滤null值
⽅法⼀:使⽤yml配置⽅式
spring:
jackson:
default-property-inclusion: non_null
⽅法⼆:使⽤Bean注⼊⽅式配置
@Configuration
public class MyJacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = ateXmlMapper(false).build();
// 通过该⽅法对mapper对象进⾏设置,所有序列化的对象都将按改规则进⾏系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为空("")或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量// Include.NON_NULL 属性为NULL 不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// 允许出现单引号
return objectMapper;
}
}
⽅法三:重写WebMvcConfigurationSupport的configureMessageConverters
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
for(HttpMessageConverter converter : converters){
if(converter instanceof MappingJackson2HttpMessageConverter){
ObjectMapper mapper =((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
}
⽅法四:重写WebMvcConfigurer的configureMessageConverters
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
for(HttpMessageConverter converter : converters){
if(converter instanceof MappingJackson2HttpMessageConverter){
ObjectMapper mapper =((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
}
}
使⽤前三种种⽅式配置时需注意:
只要使⽤@EnableWebMvc这个注解或者是继承WebMvcConfigurationSupport类,则以上三种配置⽆效。
这是因为加了@EnableWebMvc加了这个注解后Springboot加载的是WebMvcConfigurationSupport中的配置项,⽽不使⽤WebMvcAutoConfiguration引⼊的配置项。也就是说⽆论是使⽤@EnableWebMvc还是WebMvcConfigurationSupport,都会禁⽌Spring Boot的⾃动装配,同时也不能⾃动读取 application.properties 或 l ⽂件中的配置(更详细的解释参考),所以前两种⽅法也就⽆效啦。
那么为什么第三种⽅法也⽆效呢?阅读,发现官⽅的解释如下:
Finally, if you opt out of the Spring Boot default MVC configuration by providing your own @EnableWebMvc
configuration, you can take control completely and do everything manually by using getMessageConverters from WebMvcConfigurationSupport.
也就是说可以使⽤ WebMvcConfigurationSupport 中的 getMessageConverters ⼿动执⾏所有操作,但
是这样的话显然要⿇烦得多,不如直接实现WebMvcConfigurer来得快。
终上所述,⼤多数时我们在SpringBoot中并不需要使⽤@EnableWebMvc注解或者继承WebMvcConfigurationSupport类,因为这样的话会是⾃动配置失效从⽽需要⼿动进⾏配置,⽽使⽤Springboot的⾃动配置就可以满⾜⼤部分的要求,以下是
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors,
formatters, view controllers, and other features), you can add your own @Configuration class of type
WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of
RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with
@EnableWebMvc.
FastJson全局过滤null值
⽅法⼀:实现WebMvcConfigurer
原先的配置是:
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
//创建fastJson消息转换器
FastJsonHttpMessageConverter fastConverter =new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig =new FastJsonConfig();
//修改配置返回内容的过滤
//WriteNullListAsEmpty :List字段如果为null,输出为[],⽽⾮null
//WriteNullStringAsEmpty :字符类型字段如果为null,输出为"",⽽⾮null
//DisableCircularReferenceDetect :消除对同⼀对象循环引⽤的问题,默认为false(如果不配置有可能会进⼊死循环)
//WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,⽽⾮null
//WriteMapNullValue:是否输出值为null的字段,默认为false
fastJsonConfig.setSerializerFeatures(
SerializerFeature.QuoteFieldNames,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteEnumUsingToString,
// SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
}
但是运⾏后发现并没有过滤null值:
参考这篇博客:。原因是Springboot⾃带的jackson的converter把我们配置的fastjson的converter覆盖了,所以需要保证我们配置的fastjson的converter在jackson的后⾯即可,因此将配置修改为:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
while(iterator.hasNext()){
HttpMessageConverter<?> converter = ();
if(converter instanceof MappingJackson2HttpMessageConverter){
//将springboot的jackson的消息转换器移除
}
}
//创建fastJson消息转换器
FastJsonHttpMessageConverter fastConverter =new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig =new FastJsonConfig();
//修改配置返回内容的过滤
//WriteNullListAsEmpty :List字段如果为null,输出为[],⽽⾮null
//WriteNullStringAsEmpty :字符类型字段如果为null,输出为"",⽽⾮null
//DisableCircularReferenceDetect :消除对同⼀对象循环引⽤的问题,默认为false(如果不配置有可能会进⼊死循环)
//WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,⽽⾮null
//WriteMapNullValue:是否输出值为null的字段,默认为false
fastJsonConfig.setSerializerFeatures(
SerializerFeature.QuoteFieldNames,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteEnumUsingToString,
// SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
原以为成功了,但是调⽤接⼝时报了错:
java.lang.IllegalArgumentException: Content-Type cannot contain wildcard type '*'
参考后,将配置信息修改为:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
while(iterator.hasNext()){
HttpMessageConverter<?> converter = ();
if(converter instanceof MappingJackson2HttpMessageConverter){
}
}
/
/创建fastJson消息转换器
FastJsonHttpMessageConverter fastConverter =new FastJsonHttpMessageConverter();
//升级最新版本需加=============================================================
List<MediaType> supportedMediaTypes =new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
fastConverter.setSupportedMediaTypes(supportedMediaTypes);
//创建配置类
FastJsonConfig fastJsonConfig =new FastJsonConfig();
//修改配置返回内容的过滤
//WriteNullListAsEmpty :List字段如果为null,输出为[],⽽⾮null
//WriteNullStringAsEmpty :字符类型字段如果为null,输出为"",⽽⾮null
//DisableCircularReferenceDetect :消除对同⼀对象循环引⽤的问题,默认为false(如果不配置有可能会进⼊死循环)
//WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,⽽⾮null
fastjson常用方法//WriteMapNullValue:是否输出值为null的字段,默认为false
fastJsonConfig.setSerializerFeatures(
SerializerFeature.QuoteFieldNames,
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteEnumUsingToString,
// SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
经过千⾟万苦后终于过滤null值:
⽅法⼆:继承WebMvcConfigurationSupport
同样实现configureMessageConverters⽅法,配置与⽅法⼀的最终配置⼀样。但是考虑到使⽤WebMvcConfigurationSupport⽅式来实现会产⽣⼀些问题(如前所述),所以还是使⽤implements WebMvcConfigurer⽅式⽐较保险。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论