gpt4 book ai didi

java - 如何根据 Java 中指定的版本规范验证 json 模式

转载 作者:行者123 更新时间:2023-11-30 03:00:42 27 4
gpt4 key购买 nike

给定一个像这样的 json 模式..

    {   "$schema": "http://json-schema.org/draft-04/schema#",   "title": "Product",   "description": "A product from Acme's catalog",   "type": "object",   "properties": {      "id": {         "description": "The unique identifier for a product",         "type": "integer"      },      "name": {         "description": "Name of the product",         "type": "string"      },      "price": {         "type": "number",         "minimum": 0,         "exclusiveMinimum": true      }   },   "required": ["id", "name", "price"]}

如何验证此 json 架构是否符合它指定的 $schema,在本例中为 Draft-04..

java中有没有可以做到这一点的包?我可以使用类似 https://github.com/everit-org/json-schema 的东西吗?或者只是根据其模式验证 json 文档?

谢谢。

最佳答案

从每个 JSON 模式链接的模式实际上是 JSON 模式的一种“元模式”,因此您实际上可以按照您的建议使用它来验证模式。

假设我们已将元架构保存为名为 meta-schema.json 的文件,并将潜在架构保存为 schema.json。首先,我们需要一种方法将这些文件加载​​为 JSONObjects:

public static JSONObject loadJsonFromFile(String fileName) throws FileNotFoundException {
Reader reader = new FileReader(fileName);
return new JSONObject(new JSONTokener(reader));
}

我们可以加载元架构,并将其加载到您链接的 json-schema 库中:

JSONObject metaSchemaJson = loadJsonFromFile("meta-schema.json");
Schema metaSchema = SchemaLoader.load(metaSchemaJson);

最后,我们加载潜在的架构并使用元架构对其进行验证:

JSONObject schemaJson = loadJsonFromFile("schema.json");
try {
metaSchema.validate(schemaJson);
System.out.println("Schema is valid!");
} catch (ValidationException e) {
System.out.println("Schema is invalid! " + e.getMessage());
}

鉴于您发布的示例,这将打印“架构有效!”。但是,如果我们要引入一个错误,例如将 "name" 字段的 "type" 更改为 "foo" 而不是“string”,我们会得到以下错误:

Schema is invalid! #/properties/name/type: #: no subschema matched out of the total 2 subschemas

关于java - 如何根据 Java 中指定的版本规范验证 json 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36075449/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com