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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With