头图

问题

后台接收 Json 参数时有以下要求:

  • 指定时间格式
  • 忽略不识别的字段
  • 忽略不识别的枚举

一般是配置 ObjectMapper 即可生效

配置 ObjectMapper

@Bean
@Primary
public ObjectMapper objectMapper() {
    return new ObjectMapper()
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}

如上配置没有生效

配置 Jackson2ObjectMapperBuilderCustomizer

@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> builder
            .featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .featuresToEnable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
            .simpleDateFormat("yyyy-MM-dd HH:mm:ss");
}

也不生效

解决方案

解决方案引用自 Jackson2ObjectMapperBuilderCustomizer不生效解决

不生效的原因一般是 MappingJackson2HttpMessageConverter 对象在程序启动时创建了多个,我们只要将多余的去掉,并重新添加 MappingJackson2HttpMessageConverter 的 bean 就可以了

问题根源

基础包中配置了 MappingJackson2HttpMessageConverter,导致应用服务工程中配置的 ObjectMapper 无效

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private RequestApiInterceptor requestApiInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestApiInterceptor).addPathPatterns("/**");
    }

    @Bean
    public RequestApiInterceptor restfulApiInterceptor() {
        return new RequestApiInterceptor();
    }

    /**
     * 解决controller返回string类型数据错误
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0, new MappingJackson2HttpMessageConverter());
    }
}

关键代码

在应用服务工程中按如下配置功能生效

@Configuration
public class ConvertConfiguration implements WebMvcConfigurer {

    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        ObjectMapper objectMapper = new ObjectMapper()
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return new MappingJackson2HttpMessageConverter(objectMapper);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.removeIf(MappingJackson2HttpMessageConverter.class::isInstance);
        converters.add(0, mappingJackson2HttpMessageConverter());
    }

}

等灯的邓
19 声望0 粉丝