如何在 Spring Boot 应用程序中配置 Jackson 而不覆盖纯 Java 中的 springs 默认设置 [英] How to configure Jackson in spring boot application without overriding springs default setting in pure java
问题描述
在我的 Spring Boot 应用程序中,我使用 Jackson 通过在需要的地方注入 ObjectMapper
来序列化对象.我找到了这个答案:https://stackoverflow.com/a/32842962/447426但是这个创建了一个新的映射器 - 使用 jacksons 默认设置.
In my spring boot application i am using Jackson to serialize objects by injecting the ObjectMapper
where needed.
I found this answer: https://stackoverflow.com/a/32842962/447426
But this one creates a new mapper - with jacksons default settings.
另一方面,我发现 this 在官方文档中.我没有真正理解.没有示例代码.
On the other hand i found this in official docu. I didn't really understand. There is no example code.
那么如何在 Spring 的默认对象映射器的基础上配置 springs ObjectMapper 呢?
So how to configure springs ObjectMapper on base of Spring's default object mapper?
此配置应在ObjectMapper"上处于活动状态;无论在哪里注射.
This configuration should be active on "ObjectMapper" whereever injected.
推荐答案
你应该使用 Jackson2ObjectMapperBuilderCustomizer
来解决这个问题
You should use Jackson2ObjectMapperBuilderCustomizer
for this
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Add your customization
// jacksonObjectMapperBuilder.featuresToEnable(...)
}
};
}
}
因为 Jackson2ObjectMapperBuilderCustomizer
是一个函子,Java 8 支持更紧凑的代码:
Because a Jackson2ObjectMapperBuilderCustomizer
is a functor, Java 8 enables more compact code:
@Configuration
public class JacksonConfiguration {
@Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
return builder -> {
builder.featuresToDisable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// Add your customization
// builder.featuresToEnable(...)
};
}
}
}
这篇关于如何在 Spring Boot 应用程序中配置 Jackson 而不覆盖纯 Java 中的 springs 默认设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!