乐趣区

关于spring-mvc:Spring-Boot-ObjectMapper-配置不生效问题

问题

后盾接管 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());
    }

}
退出移动版