3

I am customizing treatment of collections in my Jackson's object mapper in my Spring Boot config by constructing a new mapper like so

@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));

}

While this works, I understand that a more elegant approach is to use Jackson2ObjectMapperBuilderCustomizer :

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

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

        }
    };
}

How do I implement ObjectMapper collection tweaks above via Jackson2ObjectMapperBuilder ?

jenn_cole
  • 31
  • 1
  • 5

2 Answers2

1

You can use a simple Module defined locally, like in this other use case. The SetupContext also has a configOverride() method, just like the ObjectMapper itself.

Frank Pavageau
  • 11,477
  • 1
  • 43
  • 53
0

No idea ? I'm interested to do the same just to add :

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

Because @JsonFormat(shape = JsonFormat.Shape.OBJECT) doesn't work well ( https://github.com/FasterXML/jackson-databind/issues/1419 ) and but after Jackson 2.5 it is the only solution (but requires 2.9.x) to restore the previous behavior without writing a custom serializer.