Reputation: 5432
I'm using spring-boot and want to customize the ObjectMapper created.
What I want to do is be able to serialize objects that do not have a getter or setters. Before this could be done by putting JsonAutoDetect.Visibility.ANY on the ObjectMapper.
But how can I enable this feature using the Jackson2ObjectMapperBuilder bean I'm currently exposing ?
Upvotes: 7
Views: 11154
Reputation: 18010
I spend a half of day to play with different settings. So I manage to work it (1.3.2.RELEASE) when:
@Configuration
annotated config class (not extended from WebMvcConfigurerAdapter
)@EnableWebMvc
Then Jackson2ObjectMapperBuilder objectMapperBuilder
solution is
work, but spring.jackson.serialization.indent_output: true
in properties ignored.
At last I finished with
@Autowired(required = true)
public void configeJackson(ObjectMapper objectMapper) {
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
}
But all this is puzzle for me. I wrote a question about any explanation of all this magic in order to have some undestanding and solve problem not by trial-and-error method: Are there any Spring Boot documentation for understanding how web mvc configuration is work?
Upvotes: 1
Reputation: 1470
If you want to keep the ObjectMapper configurable through the spring.jackson.* properties that Spring Boot provides, then you better don't define your own Jackson2ObjectMapperBuilder bean (check JacksonObjectMapperBuilderConfiguration inside JacksonAutoConfiguration class for details).
What you can do instead is this:
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
return mapperBuilder.build().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
}
Upvotes: 8
Reputation: 116091
You can use a Jackson2ObjectMapperBuilder
subclass that overrides the configure(ObjectMapper)
method:
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
return new Jackson2ObjectMapperBuilder() {
@Override
public void configure(ObjectMapper objectMapper) {
super.configure(objectMapper);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
}
};
}
Upvotes: 9