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

如何用Java将Draft 2020-12版本JSON Schema转换为JSON?

支持JSON Schema Draft 2020-12的Java实例生成库推荐

如果你需要从Draft 2020-12版本的JSON Schema生成符合要求的JSON实例,推荐使用NetworkNT JSON Schema Validator——这个库不仅支持Draft 2020-12的所有关键字(包括$defs、$ref这类嵌套引用),还内置了实例生成功能,完全适配你的需求。

依赖配置(Maven)

在pom.xml中添加以下依赖:

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>1.0.89</version> <!-- 建议使用最新稳定版 -->
</dependency>

示例代码

结合你提供的Schema,以下代码可以生成类似示例的JSON输出:

import com.networknt.schema.JsonSchema;
import com.networknt.schema.JsonSchemaFactory;
import com.networknt.schema.SpecVersion;
import com.networknt.schema.generator.JsonGenerator;
import com.networknt.schema.generator.JsonGeneratorConfig;
import com.networknt.schema.generator.JsonGeneratorConfigBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SchemaToJsonGenerator {
    public static void main(String[] args) throws IOException {
        // 加载你的Draft 2020-12 Schema文件
        try (InputStream schemaInput = Files.newInputStream(Paths.get("your-schema-file.json"))) {
            // 指定使用Draft 2020-12版本
            JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
            JsonSchema schema = schemaFactory.getSchema(schemaInput);

            // 配置生成规则:比如数组元素数量、字符串长度范围等
            JsonGeneratorConfig generatorConfig = new JsonGeneratorConfigBuilder()
                    .setArrayMinItems(1)
                    .setArrayMaxItems(2)
                    .setStringMinLength(5)
                    .setStringMaxLength(25)
                    .build();

            // 生成JSON实例
            JsonGenerator generator = schema.createGenerator(generatorConfig);
            System.out.println(generator.generate());
        }
    }
}

功能说明

  • 自动识别Schema中的type、required、items等关键字,生成符合约束的JSON数据
  • 支持$defs和$ref的嵌套引用,正确解析并生成嵌套对象结构
  • 可通过JsonGeneratorConfig自定义生成规则(比如数组长度、字符串长度、数值范围等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:52:06