如何在Spring MVC(非Spring Boot)应用程序中自定义Jackson [英] How to customize Jackson in Spring MVC (not Spring Boot) application
问题描述
Spring MVC 4.3.29和Java 8(当前平台限制),以及大多数XML配置,除了一些注释注释的Controller类.
Spring MVC 4.3.29 and Java 8 (current platform constraints), and mostly XML configuration, except for some Controller classes that are annotation-scanned.
简而言之,我想让Spring JSON反序列化自动使用ObjectMapper
实例,并将其FAIL_ON_UNKNOWN_PROPERTIES
设置回true
.
In short, I want to get the ObjectMapper
instance being used automatically by Spring JSON deserialization, and I want to set its FAIL_ON_UNKNOWN_PROPERTIES
back to true
.
我看到了相关 <一个href ="https://stackoverflow.com/questions/30060006/how-do-i-obtain-the-jackson-objectmapper-in-use-by-spring-4-1">问题,但是所有示例似乎都是 Spring Boot 和/或Java配置.在我的WebSphere环境中,所有建议的@Autowired
Bean(映射器,Builder等)都没有任何值.
I see several related questions, but all the examples seem to be Spring Boot and/or Java configuration. And none of the suggested @Autowired
beans (Mapper, Builder, etc.) have any values at all in my WebSphere environment.
希望我只是在某个地方缺少一些简单的胶水.
Hopefully I'm just missing some simple glue somewhere.
B,我以为我已经拥有了它:
Bah, I thought I had it with this:
@Configuration
public class CustomWebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
((MappingJackson2HttpMessageConverter) converter).getObjectMapper().
enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
break;
}
}
}
}
通过调试器,我可以看到它被命中并更改了预期的标志.但是,当使用时,该行为无效.我不再有任何XML替代,但是我仍然有"master"标记. <mvc:annotation-driven/>
在那里.我想知道它们是否使彼此混淆...
And with my debugger I can see that it is being hit and changing the expected flag. But when used, the behavior is not in effect. I no longer have any XML overrides in place, but I do still have the "master" <mvc:annotation-driven/>
there. I wonder if those are confusing each other...
推荐答案
好,是的,只要与@EnableWebMvc
而不是<mvc:annotation-driven/>
结合使用,它就可以工作:
Ok, yes, this works as long as it's combined with @EnableWebMvc
rather than <mvc:annotation-driven/>
:
@EnableWebMvc
@Configuration
public class CustomWebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter) {
((MappingJackson2HttpMessageConverter) converter).getObjectMapper().
enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
break;
}
}
}
}
这篇关于如何在Spring MVC(非Spring Boot)应用程序中自定义Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!