【问题标题】:How to auto convert camel case request body to snake case protobuf message in Spring Boot如何在 Spring Boot 中将骆驼案例请求正文自动转换为蛇案例 protobuf 消息
【发布时间】:2022-01-14 13:02:06
【问题描述】:

我有一个这样的端点

@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 的样式指南,我应该对字段使用蛇形大小写样式,所以当客户端调用此端点时,请求正文应该是这样的。

{ "client_id": "abcdefg"}

但是,对于 JSON 样式指南,该字段应该使用驼峰式大小写,像这样

{ "clientId": "abcdefg"}

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

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

@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));
    }

似乎它应该自动将骆驼案例 json 转换为蛇案例 protobuf。但它并不如我所愿。

【问题讨论】:

    标签: java spring spring-boot protobuf-java


    【解决方案1】:

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

    @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 2020-02-10
      • 2016-01-16
      • 2020-05-03
      相关资源
      最近更新 更多