Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring Jackson mixin in Spring Boot application

Tags:

I created a mixin for my class. The mixin itself works fine, it's not the issue that most people have where they mix faterxml/codehaus annotations. I tested it in a unit test, creating the ObjectMapper "by hand" while using the addMixIn method - it worked just fine.

I want to use that mixin to modify the response jsons returned from my REST endpoints. I've tried to customize Spring Boot's ObjectMapper in many different ways:

BuilderCustomizer:

@Bean
public Jackson2ObjectMapperBuilderCustomizer addMixin(){
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
            jacksonObjectMapperBuilder.mixIn(MyClass.class, MyClassMixin.class);                
        }
    };
}

Builder:

@Bean
Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
    return new Jackson2ObjectMapperBuilder().mixIn(MyClass.class, MyClassMixin.class);
}

Converter:

@Bean
public MappingJackson2HttpMessageConverter configureJackson(){
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(MyClass.class, MyClassMixin.class);
    converter.setObjectMapper(mapper);
    return converter;
}

ObjectMapper:

@Autowired(required = true)
public void configureJackon(ObjectMapper jsonMapper){
    jsonMapper.addMixIn(MyClass.class, MyClassMixin.class);
}

None of these work.

like image 471
dkaras Avatar asked Jul 05 '18 13:07

dkaras


2 Answers

This might depend on Spring Boot version but as per Customize the Jackson ObjectMapper defining a new Jackson2ObjectMapperBuilderCustomizer bean is sufficient

The context’s Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.

like image 101
Karol Dowbecki Avatar answered Sep 28 '22 18:09

Karol Dowbecki


As of Spring Boot 2.7, there is built-in support for mixins.

Adding the following annotation:

@JsonMixin(MyClass::class)
class MyClassMixin{

will register mixin in the auto-configured ObjectMapper.

like image 22
pixel Avatar answered Sep 28 '22 17:09

pixel