首页 > 解决方案 > Json 模式验证失败

问题描述

我有以下依赖项pom.xml

 <!-- https://github.com/everit-org/json-schema -->
               <dependency>
                   <groupId>com.github.everit-org.json-schema</groupId>
                   <artifactId>org.everit.json.schema</artifactId>
                   <version>1.11.1</version>
               </dependency>

               <!-- https://mvnrepository.com/artifact/org.json/json -->
               <dependency>
                   <groupId>org.json</groupId>
                   <artifactId>json</artifactId>
                   <version>20190722</version>
               </dependency>

这是我的 json 架构

{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "id": "test",
    "title": "test-json validation",
    "description": "This schema should define the structure of the test json",
    "allOf": [
        {
            "$ref": "classpath:/jsonSchema/header/test.json#/definitions/test"
        },
        {
            "$ref": "classpath:/jsonSchema/rows/test.json#/definitions/test"
        }
    ],
    "properties": {
        "version": {
            "type": "array",
            "items": {
                "type": "string",
                "enum": [
                    "2.0",
                    "2.1"
                ]
            }
        }
    },
    "required": [
        "version"
    ]
}

这就是我想要实现的目标

public Schema createSchema(String schemaPath) throws IOException {

        Schema schema = null;
        try (InputStream inputStream = new ClassPathResource(schemaPath).getInputStream()) {
            JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
            schema = SchemaLoader.load(rawSchema);
        }
        return schema;
    }

我得到以下异常:

SchemaException:类路径:/jsonSchema/header/order_header.json#/definitions/order_header/properties/order_header/properties/origin/properties/locale:预期类型是布尔值或 JsonObject 之一,发现:org.everit.json.schema 处的字符串.loader.LoadingState.createSchemaException(LoadingState.java:142) 在 org.everit.json.schema.loader.JsonValue$Multiplexer.multiplexFailure(JsonValue.java:50) 在 org.everit.json.schema.loader.JsonValue$Multiplexer .lambda$requireAny$1(JsonValue.java:45) at java.util.Optional.orElseThrow(Optional.java:290) at org.everit.json.schema.loader.JsonValue$Multiplexer.requireAny(JsonValue.java:45)在 org.everit.json.schema.loader.SchemaLoader.load(SchemaLoader.java:434) [6x]

标签: javajsonschemajson-schema-validator

解决方案


对象中的值properties必须是模式。

在你的情况下,你已经把"string"它作为一个价值。

您看到的错误是 SCHEMA 无法验证,因为它希望看到一个布尔值或 JSON 对象,但获取一个字符串,用于locale.


推荐阅读