signed

QiShunwang

“诚信为本、客户至上”

SpringBoot Jackson下划线风格返回

2021/5/14 21:06:30   来源:

xi前提: 我使用的SpringBoot版本为2.4.5, Jackson版本为2.11.4

今天优化自己的一个SpringBoot项目时, 发现一个问题: 通过JSON返回的response中的属性名都是Java中的驼峰形式, 这让前端开发很难受啊. 

尝试了度娘搜索的前几个配置方法配置jackson, 结果都不行.或许是我的版本太新吧...

最终在google中找到正确的配置方案:

java - How to set PropertyNamingStrategy for RestTemplate in SpringBoot? - Stack Overflow

A shorter answer is to use the Spring's objectMapper. The benefit is that it shares the same configuration in application.properties. So you can set spring.jackson.property-naming-strategy=SNAKE_CASE or whatever there, and it's consistent across the entire application including RestTemplate. Code as follows.

@Configuration
@RequiredArgsConstructor
public class HTTPConfig {
    public final ObjectMapper objectMapper;  // provided by spring

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder()
            .messageConverters(new MappingJackson2HttpMessageConverter(objectMapper))
            .build();
    }
}

 希望对你有帮助.