You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过OpenAPI Generator生成kotlin.Pair类型请求体?

如何让OpenAPI Generator生成对应Kotlin Pair类型的RequestBody?

问题描述

我希望定义一个requestBody,使其通过OpenAPI Generator生成后对应kotlin.Pair类型。尝试了以下配置但未成功:

requestBody:
  required: true
  content:
    application/json:
      schema:
        type: object
        properties:
          first:
            type: string
          second:
            type: string

请问该需求是否可行?如果可行,具体该如何实现?

解决方案

该需求完全可行,需要通过OpenAPI Schema扩展+生成器配置结合实现,具体步骤如下:

1. 修改OpenAPI Schema,添加Kotlin类型映射扩展

在原有schema中添加x-kotlin-type扩展字段,明确指定要生成的Kotlin类型为kotlin.Pair并声明泛型参数。修改后的配置如下:

requestBody:
  required: true
  content:
    application/json:
      schema:
        type: object
        properties:
          first:
            type: string
          second:
            type: string
        # 指定映射到Kotlin Pair<String, String>
        x-kotlin-type: "kotlin.Pair<String, String>"

如果需要其他类型的Pair(比如Pair<Int, Boolean>),只需修改x-kotlin-type中的泛型参数,同时对应调整first和second的schema类型即可。

2. 配置OpenAPI Generator启用扩展支持

生成代码时,需要通过参数开启扩展识别功能,确保生成器读取x-kotlin-type并生成对应的类型:

  • 命令行方式:
    openapi-generator generate -i your-spec.yaml -g kotlin -o generated-code --additional-properties=useExtensions=true
    
  • Gradle插件方式:
    openApiGenerate {
      generatorName = "kotlin"
      inputSpec = "$rootDir/src/main/resources/your-spec.yaml".toString()
      outputDir = "$buildDir/generated/openapi"
      additionalProperties = [
        useExtensions: "true"
      ]
    }
    
  • Maven插件方式:
    <plugin>
      <groupId>org.openapitools</groupId>
      <artifactId>openapi-generator-maven-plugin</artifactId>
      <version>6.6.0</version> <!-- 推荐使用v6.0+版本 -->
      <executions>
        <execution>
          <goals>
            <goal>generate</goal>
          </goals>
          <configuration>
            <inputSpec>${project.basedir}/src/main/resources/your-spec.yaml</inputSpec>
            <generatorName>kotlin</generatorName>
            <output>${project.build.directory}/generated-sources/openapi</output>
            <additionalProperties>
              <useExtensions>true</useExtensions>
            </additionalProperties>
          </configuration>
        </execution>
      </executions>
    </plugin>
    

注意事项

  • 推荐使用OpenAPI Generator v6.0及以上版本,旧版本可能不支持x-kotlin-type扩展
  • 生成的kotlin.Pair会自动绑定JSON中的first和second字段,无需额外编写序列化逻辑
  • 如果你的项目使用了自定义序列化库(如Jackson),需确保其支持Kotlin Pair的JSON序列化/反序列化

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:10:17