RestTemplate 在 Spring REST 中不使用 Snake Case 返回值

mik*_*ang 3 json camelcasing resttemplate

我在 application.properties 中有带有属性的 REST API,如下所示:

spring.jackson.property-naming-strategy: CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
Run Code Online (Sandbox Code Playgroud)

一切都好!但是当我使用 RestTemplate 进行如下操作时,我发现 Snake Case 中的所有键都为空(例如 nameEnglish),但常规键名可以(例如 rank),我该如何解决这个问题?

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"id"})
@Entity
public class Brand implements Serializable {
    private static final long serialVersionUID = 9165709510160554127L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Version
    private Integer version;

    private String nameChinese;
    private String nameEnglish;
    private String rank;
}
Run Code Online (Sandbox Code Playgroud)

我保存了如下数据:

Saved Brand: Brand(id=1, version=1, nameChinese=??, nameEnglish=Lego, rank=Top)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试如下代码时:

Brand brands = restTemplate.getForObject("http://localhost:8080/api/brand/lego", Brand.class);
System.out.println(brands);
Run Code Online (Sandbox Code Playgroud)

结果如下,您将看到所有 Camel Case 属性都为 null,尽管我为它们设置了值:

Saved Brand: Brand(id=1, version=1, nameChinese=null, nameEnglish=null, rank=Top)
Run Code Online (Sandbox Code Playgroud)

CocoaRestCLient 的 Json 格式结果

{
    "id": 1,
    "country_chinese": "??",
    "version": 1,
    "homepage_url": "http://www.lego.com",
    "country_english": "Finland",
    "name_english": "Lego",
    "rank": "Top",
    "name_chinese": "??"
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ksa 6

我认为您在application.properties. 正确的值是:

spring.jackson.property-naming-strategy=CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
Run Code Online (Sandbox Code Playgroud)

或者

spring.jackson.property-naming-strategy=com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy
Run Code Online (Sandbox Code Playgroud)

请参阅Spring Boot 参考指南中的附录 A. 常见应用程序属性

spring.jackson.property-naming-strategy= # Jackson 的 PropertyNamingStrategy 的常量之一。也可以是 PropertyNamingStrategy 子类的完全限定类名。


Min*_*ing 6

您可能想检查是否RestTemplate使用了 spring 提供的 objectMapper。就我而言,我添加了这个并且它起作用了。

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

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder()
            .messageConverters(new MappingJackson2HttpMessageConverter(objectMapper))
            .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

假设你已经spring.jackson.property-naming-strategy=SNAKE_CASEapplication.properties