简体   繁体   中英

Configure Jackson to use SNAKE_CASE “globally” in Spring Boot 2.0.0.M1

I'm using Spring Boot 2.0.0.M1 (hence Spring 5.0.0.RC1 ). I'm trying to configure it to make use of PropertyNamingStrategy.SnakeCaseStrategy.SNAKE_CASE but I doesn't work so far.

I've tried:

  1. The application.yml file with:

     spring: jackson: property-naming-strategy: SNAKE_CASE 
  2. Configuring a Jackson2ObjectMapperBuilder bean:

     @Bean @Primary open fun jacksonBuilder(): Jackson2ObjectMapperBuilder { val jacksonMapperBuilder = Jackson2ObjectMapperBuilder() .failOnUnknownProperties(false) .modules(JavaTimeModule(), KotlinModule()) .propertyNamingStrategy(PropertyNamingStrategy.SnakeCaseStrategy.SNAKE_CASE) logger.info { "Jackson2ObjectMapperBuilder configured successfully..." } return jacksonMapperBuilder } 
  3. Configuring an ObjectMapper bean:

     @Bean @Primary open fun objectMapper(): ObjectMapper { val objectMapper = ObjectMapper() objectMapper.registerModule(JavaTimeModule()) objectMapper.registerModule(KotlinModule()) objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCaseStrategy.SNAKE_CASE) logger.info { "ObjectMapper configured successfully..." } return objectMapper } 

The only way I've found to make it work it by annotating every single class with @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class) ...but that's not a solution for my case.

Any other options?


This is the dependencies "section" in my build.gradle.kts file:

dependencies {
  compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
  compile("com.fasterxml.jackson.module:jackson-module-kotlin")
  compile("io.github.microutils:kotlin-logging:1.4.4")
  //compile("io.projectreactor:reactor-kotlin-extensions")
  compile("org.springframework.boot:spring-boot-starter-actuator")
  compile("org.springframework.boot:spring-boot-starter-data-mongodb-reactive")
  compile("org.springframework.boot:spring-boot-starter-webflux")
  compile(kotlin("stdlib"))

  testCompile("io.projectreactor.addons:reactor-test")
  testCompile("org.springframework.boot:spring-boot-starter-test")
}

UPDATE:

This was indeed fixed on M3 ; if you need the SnakeCaseStrategy.SNAKE_CASE the setting(s) in application.yml are enough.

As the Web-Flux module documentation states:

The spring-core module provides reactive Encoder and Decoder contracts that enable the serialization of a Flux of bytes to and from typed objects.

Apparently the automatically configured ObjectMapper by JacksonAutoConfiguration won't be picked up by the WebFluxAutoConfiguration and WebFluxConfigurationSupport when configuring an instance of Jackson2JsonEncoder . This issue already reported in here and currently planned for M3 milestone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM