Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson2ObjectMapperBuilder enable field visibility ANY

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 ?

like image 776
Jonas Geiregat Avatar asked Apr 22 '15 20:04

Jonas Geiregat


People also ask

What is Jackson2ObjectMapperBuilder?

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.

Does Jackson use getter or field?

Jackson by default uses the getters for serializing and setters for deserializing.

Does Jackson use getters and setters?

Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

Is there any annotation to make non public field serializable without getters?

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.


1 Answers

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

    };

}
like image 102
Andy Wilkinson Avatar answered Oct 08 '22 18:10

Andy Wilkinson