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 ?
public class Jackson2ObjectMapperBuilder extends Object. A builder used to create ObjectMapper instances with a fluent API. It customizes Jackson's default properties with the following ones: MapperFeature.
Jackson by default uses the getters for serializing and setters for deserializing.
Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.
If there's no public fields available then public getters/setters are used. We can customize this default behavior by the use of @JsonAutoDetect annotation. @JsonAutoDetect annotation can be used to specify access visibility rules for fields and/or methods.
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);
}
};
}
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