Jackson2ObjectMapperBuilder allows ANY field visibility

I am using spring-boot and want to customize the created ObjectMapper.

I want to serialize objects that don't have getters or setters. Before this can be done, put JsonAutoDetect.Visibility.ANY in ObjectMapper.

But how do I enable this feature with the Jackson2ObjectMapperBuilder bean that I am currently showing?

+4
source share
3 answers

You can use a subclass Jackson2ObjectMapperBuilderthat overrides the method configure(ObjectMapper):

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
    return new Jackson2ObjectMapperBuilder() {

        @Override
        public void configure(ObjectMapper objectMapper) {
            super.configure(objectMapper);
            objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        }

    };

}
+8
source

, ObjectMapper spring.jackson. *, Spring Boot, Jackson2ObjectMapperBuilder bean ( JacksonObjectMapperBuilderConfiguration JacksonAutoConfiguration).

:

@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
    return mapperBuilder.build().setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
}
+5

, . (1.3.2.RELEASE), :

  • jackson @Configuration ( WebMvcConfigurerAdapter)
  • @EnableWebMvc

Jackson2ObjectMapperBuilder objectMapperBuilder , spring.jackson.serialization.indent_output: true .

,

 @Autowired(required = true)
 public void configeJackson(ObjectMapper objectMapper) {
     objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
            .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
 }

. , - : - Spring , web mvc?

0

Source: https://habr.com/ru/post/1584112/


All Articles