Webclient + Jackson: how to setup deserialization to convert snake_case into camelCase?
Asked Answered
M

3

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?

Merovingian answered 30/12, 2019 at 18:48 Comment(1)
@MichałZiober Sorry, I was on Vacations. I just tested your solution and it works!Merovingian
F
11

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:

Freely answered 30/12, 2019 at 19:18 Comment(0)
D
1

You can add annotation to your model class:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Model {
  String camelCase; //will be camel_case in json
}
Depressomotor answered 30/12, 2019 at 18:55 Comment(1)
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)Merovingian
M
-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
Multistage answered 30/12, 2019 at 19:3 Comment(2)
But if I setup it globally it means that my API is also going to respond with snake_case, right? I don't want to change serialization, only deserialization.Merovingian
Agree, this is a good question then. My solution influences on both.Multistage

© 2022 - 2024 — McMap. All rights reserved.