繁体   English   中英

如何在 Spring Boot 中自动将 camel case 请求正文转换为 snake case protobuf 消息

[英]How to auto convert camel case request body to snake case protobuf message in Spring Boot

我有一个这样的端点

@PostMapping(value = "/create")
    public Mono<?> issueToken(@RequestBody IssuePayTokenRequest request) {
        return Mono.fromCallable(() -> tokenManagementService.issuePayToken(request)).subscribeOn(Schedulers.boundedElastic());
    }

而 IssuePayTokenRequest 是一个 protobuf 消息,就像这样

message IssuePayTokenRequest {
  string client_id = 1;
}

根据 Google protobuf 的风格指南,我应该对字段使用 snake case 风格,所以当客户端调用这个端点时,请求正文应该是这样的。

{ "client_id": "abcdefg"}

但是,对于 JSON 样式指南,该字段应使用驼峰大小写,如下所示

{ "clientId": "abcdefg"}

我可以做一些配置让 Spring Boot 自动将驼峰式请求正文转换为蛇式 protobuf 消息吗?

PS:这是遗留项目,我对Spring不熟悉,但我在Configuartion class中找到了这段代码。

@Bean
    public ObjectMapper objectMapper() {
        return new Jackson2ObjectMapperBuilder()
                .featuresToDisable(
                        JsonGenerator.Feature.IGNORE_UNKNOWN,
                        MapperFeature.DEFAULT_VIEW_INCLUSION,
                        DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                        SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
                )
                .serializationInclusion(JsonInclude.Include.ALWAYS)
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
                .modulesToInstall(ProtobufModule.class)
                .build();
    }

    @Override
    protected void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        ObjectMapper objectMapper = objectMapper();
        configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper));
        configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper));
    }

似乎它应该自动将 camel case json 转换为 snake case protobuf。 但它并不像我希望的那样工作。

尝试将此配置放在您的 DTO 上:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

或者,您可以对 objectMapper bean 进行自定义配置以影响所有对象:

@Bean
ObjectMapper objectMapper() {
 return new ObjectMapper()
  .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}

这可以通过添加以下属性来实现

spring.jackson.property-naming-strategy=SNAKE_CASE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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