我一直找不到如何在Spring Boot 1.4中使用 Jackson2ObjectMapperBuilderCustomizer.java 来自定义Jackson功能的示例。
在启动1.4定制杰克逊DOCO - http://docs.spring.io/spring-boot/docs/current- SNAPSHOT/reference/htmlsingle/#howto-customize-the- jackson-
我的配置有效,尽管我不确定这是否是使用 Jackson2ObjectMapperBuilderCustomizer.java 定制对象映射器的正确方法。 __
@Configuration public class JacksonAutoConfiguration { @Autowired private Environment env; @Bean public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder( List<Jackson2ObjectMapperBuilderCustomizer> customizers) { Jackson2ObjectMapperBuilder builder = configureObjectMapper(); customize(builder, customizers); return builder; } private void customize(Jackson2ObjectMapperBuilder builder, List<Jackson2ObjectMapperBuilderCustomizer> customizers) { for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) { customizer.customize(builder); } } private Jackson2ObjectMapperBuilder configureObjectMapper() { Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); List<String> activeProfiles = asList(env.getActiveProfiles()); if (activeProfiles.contains(SPRING_PROFILE_DEVELOPMENT)) { builder.featuresToEnable(SerializationFeature.INDENT_OUTPUT); } return builder; } }
为了提供一些上下文,该类位于我自己的REST服务的spring starter项目中,该项目仅自动配置许多东西,例如ControllerAdvice和上述的一些琐碎功能。
因此,我的目标是扩展Jackson配置,而不是覆盖启动程序或其他软件包提供的任何配置。
为了自定义ObjectMapperSpring Boot已经预先配置的Jackson ,我能够做到这一点(这里的示例是添加一个自定义解串器)。
ObjectMapper
配置类:
@SpringBootConfiguration public class Application { @Autowired private BigDecimalDeserializer bigDecimalDeserializer; ... @Bean public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() { return new Jackson2ObjectMapperBuilderCustomizer() { @Override public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) { jacksonObjectMapperBuilder.deserializerByType(BigDecimal.class, bigDecimalDeserializer); } }; } ... }
还有我的自定义反序列化器,以显示Spring如何拾取它:
@Component public class BigDecimalDeserializer extends StdDeserializer<BigDecimal> { public BigDecimalDeserializer() { super(BigDecimal.class); } @Override public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { ... } ... }