Jackson - 通过Jackson2ObjectMapperBuilderCustomizer配置集合的覆盖

时间:2016-12-14 11:35:07

标签: spring-boot jackson

我通过构建一个像这样的新映射器在我的Spring Boot配置中自定义Jackson的对象映射器中的集合处理

@Configuration
public class Config {

@Autowired(required = true)
public void objectMapper(ObjectMapper mapper) {

    mapper.configOverride(Collection.class).setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null));
    mapper.configOverride(List.class).setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null));
    mapper.configOverride(Map.class).setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_EMPTY, null));

}

虽然这有效,但我知道更优雅的方法是使用Jackson2ObjectMapperBuilderCustomizer

@Bean
public Jackson2ObjectMapperBuilderCustomizer customizeJackson2ObjectMapper() {
    return new Jackson2ObjectMapperBuilderCustomizer() {

        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder
            .indentOutput(true)
            .someOtherMethod(...)

        }
    };
}

如何通过Jackson2ObjectMapperBuilder实现上面的ObjectMapper集合调整?

2 个答案:

答案 0 :(得分:1)

您可以使用在本地定义的简单Module,就像在this other use case中一样。 SetupContext也有configOverride()方法,就像ObjectMapper本身一样。

答案 1 :(得分:0)

不知道吗?我有兴趣做同样的事情只是添加:

mapper.configOverride(Map.Entry.class).setFormat(forShape(Shape.OBJECT));

因为@JsonFormat(shape = JsonFormat.Shape.OBJECT)不能很好地工作(https://github.com/FasterXML/jackson-databind/issues/1419),但是在Jackson 2.5之后,它是唯一一种无需编写自定义序列化程序即可恢复先前行为的解决方案(但需要2.9.x)。 / p>