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

如何为Vert.x应用从Java/Kotlin数据类生成OpenAPI Schema?

Kotlin数据类生成OpenAPI Schema的可行方案

方案1:基于Jackson生态直接生成(适配性最高)

你项目已使用Jackson做序列化,可直接用Jackson官方的JSON Schema生成模块,生成的JSON Schema可直接复用在OpenAPI规范中(OpenAPI 3.0+ Schema规则是JSON Schema的超集,兼容度极高)

  • 引入依赖
    Gradle Kotlin DSL参考:
    implementation("com.fasterxml.jackson.module:jackson-module-jsonSchema:2.15.2")
    
    Maven参考:
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-jsonSchema</artifactId>
      <version>2.15.2</version>
    </dependency>
    
  • 生成代码示例
    import com.fasterxml.jackson.databind.ObjectMapper
    import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator
    import com.fasterxml.jackson.module.kotlin.registerKotlinModule
    
    // 复用你项目中已配置的ObjectMapper实例即可,保证生成规则和实际序列化规则完全一致
    val objectMapper = ObjectMapper().registerKotlinModule()
    val schemaGenerator = JsonSchemaGenerator(objectMapper)
    
    // 替换为你需要生成的Kotlin数据类
    val jsonSchema = schemaGenerator.generateSchema(YourDataClass::class.java)
    // 输出格式化后的Schema,直接复制到OpenAPI的components/schemas节点下即可
    println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema))
    

该方案会自动识别所有Jackson注解(@JsonProperty、@JsonIgnore、@JsonPropertyOrder等),生成的Schema和实际序列化行为完全对齐,不会出现规则不一致的问题。

方案2:直接生成严格OpenAPI 3.x格式Schema

如果需要严格符合OpenAPI 3.0/3.1规范的Schema结构,可使用Swagger官方的模型转换工具,不需要依赖完整的Swagger框架或Vert.x适配:

  • 引入依赖
    Gradle Kotlin DSL参考:
    implementation("io.swagger.core.v3:swagger-core:2.2.15")
    
  • 生成代码示例
    import io.swagger.v3.core.converter.ModelConverters
    import io.swagger.v3.core.util.Json
    
    // 直接生成OpenAPI规范格式的Schema集合
    val openApiSchemas = ModelConverters.getInstance().read(YourDataClass::class.java)
    // 输出结果可直接粘贴到OpenAPI规范中使用
    println(Json.pretty().writeValueAsString(openApiSchemas))
    

批量生成技巧

你可以写一个简单的单元测试类,通过类扫描工具批量扫描项目中所有Kotlin数据类所在的包,一次性生成所有Schema并导出到单独的JSON/YAML文件,直接导入到你的OpenAPI主规范文件即可,无需手动逐个处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 20:30:03