6

I'd like to avoid having to prefix my attributes with @JsonProperty("property_name") and instead just setup the Spring WebClient builder to convert all snake_cases into camelCases.

Is that possible?

bpereira
  • 966
  • 2
  • 11
  • 29

3 Answers3

10

Read 9.4.3. Customize the Jackson ObjectMapper and 10.A.4. JSON properties to be aware how many options we can define from configuration file. In your case you need to set:

spring.jackson.property-naming-strategy=SNAKE_CASE

If you want to change configuration only for deserialisation you need to customise a way how WebClient is created.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfiguration {

    @Bean
    public WebClient webClient(ObjectMapper baseConfig) {
        ObjectMapper newMapper = baseConfig.copy();
        newMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
                .codecs(configurer ->
                        configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(newMapper)))
                .build();
        return WebClient.builder()
                .baseUrl("http://localhost:8080")
                .exchangeStrategies(exchangeStrategies)
                .build();
    }
}

See:

Nicofisi
  • 1,083
  • 1
  • 15
  • 27
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
1

You can add annotation to your model class:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Model {
  String camelCase; //will be camel_case in json
}
donquih0te
  • 597
  • 3
  • 22
  • JsonNaming is for serialization only, I don't want my responses to be snake case, I want to be able to read other apis that are snake_case and convert them to camel case (only deserialization, and not serialization) – bpereira Dec 30 '19 at 19:12
-1

You can either follow this advice and apply the config only for one model.

Or you can set it up globally via appropriate property:

spring:
  jackson:
    property-naming-strategy: SNAKE_CASE
Stepan Tsybulski
  • 1,121
  • 8
  • 18