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

如何从Java类生成AWS CDK的ApiGateway JsonSchema?

从Java类自动生成AWS CDK的JsonSchema

可以通过victools/jsonschema-generator库自动从Java类生成AWS CDK所需的software.amazon.awscdk.services.apigateway.JsonSchema,无需手动编写所有字段的Schema定义。

完整实现代码

import software.amazon.awscdk.services.apigateway.RestApi;
import software.amazon.awscdk.services.apigateway.JsonSchema;
import software.amazon.awscdk.services.apigateway.Model;
import software.amazon.awscdk.services.apigateway.IModel;
import software.amazon.awscdk.services.apigateway.StageOptions;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.fasterxml.jackson.databind.JsonNode;
import my.java.project.domains.models.MyClass;

// 配置Schema生成器,适配OpenAPI规范
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_7, OptionPreset.PLAIN_JSON);
SchemaGeneratorConfig config = configBuilder
    .with(Option.EXTRA_OPEN_API_FORMAT_VALUES) // 生成符合OpenAPI的格式字段(如date-time)
    .without(Option.FLATTENED_ENUMS_FROM_TOSTRING) // 避免枚举值用toString结果
    .build();

SchemaGenerator schemaGenerator = new SchemaGenerator(config);
// 生成MyClass对应的JSON Schema字符串
JsonNode schemaNode = schemaGenerator.generateSchema(MyClass.class);
String schemaString = schemaNode.toString();

// 创建RestApi
RestApi myRestApi = RestApi.Builder.create(this, "MyRestApi")
    .restApiName("myRestApi")
    .deployOptions(StageOptions.builder()
                    .stageName("v1")
                    .tracingEnabled(true)
                    .build())
    .build();

// 生成API Gateway的Model,使用自动生成的Schema
IModel myRequestModel = Model.Builder.create(this, "MyRequestModel")
    .restApi(myRestApi)
    .contentType("application/json")
    .description("重置密码请求模型")
    .schema(JsonSchema.builder().fromString(schemaString).build())
    .build();

关键说明

  • 库依赖:需在项目中引入victools/jsonschema-generator依赖(支持Maven/Gradle)
  • Schema版本:指定SchemaVersion.DRAFT_7是因为API Gateway的Model兼容JSON Schema Draft 7,同时匹配OpenAPI 3.0规范
  • 配置项:EXTRA_OPEN_API_FORMAT_VALUES会为日期、时间等类型自动添加OpenAPI标准的format字段,让API Gateway能正确识别数据类型
  • 修正点:原示例中的SchemaBuilder.buildSchema()是错误用法,正确方式是通过schemaGenerator.generateSchema()获取JsonNode后转成字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:13:16