【问题标题】:How to validate a json schema against the version spec it specifies in Java如何根据它在 Java 中指定的版本规范验证 json 模式
【发布时间】:2016-07-04 16:19:58
【问题描述】:

给定一个像这样的 json 架构..

{ "$schema": "http://json-schema.org/draft-04/schema#", “标题”:“产品”, "description": "Acme 目录中的产品", “类型”:“对象”, “特性”: { “ID”: { "description": "产品的唯一标识符", “类型”:“整数” }, “姓名”: { "description": "产品名称", “类型”:“字符串” }, “价钱”: { “类型”:“数字”, “最小”:0, "exclusiveMinimum": true } }, “必需”:[“id”、“名称”、“价格”] }

如何验证这个 json 模式是否符合它指定的 $schema,在本例中是 draft-04..

java中有没有可以做到这一点的包? 我可以使用https://github.com/everit-org/json-schema 之类的东西,还是仅根据其架构验证 json 文档?

谢谢。

【问题讨论】:

    标签: java json schema


    【解决方案1】:

    从每个 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-04
      • 2017-06-21
      • 2016-03-13
      • 2011-02-06
      • 2016-12-20
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      相关资源
      最近更新 更多