Java - 当数组元素不遵循模式时,JSON 模式验证不会失败

问题描述 投票:0回答:1

我正在尝试验证 Java 17 中的 JSON 字符串。 目前我正在使用: com.fasterxml.jackson.core 和 com.networknt:json-schema-validator

问题是,当我在数组中输入不遵循 JSON 模式模式的元素时,不会引发任何错误。我不明白为什么? 如果我尝试使用 https://www.jsonschemavalidator.net/ 进行验证,它会失败。

数组中的元素应该是13个数字。其他所有内容都应该给出错误!

JSON 输入

只有最后一个元素是正确的

{
    "mylist": ["123Abc", "123456789012", "1234567890123"]
}

JSON 模式

{
    "$id" : "https://schema.mysite.se/myschema",
    "$schema" : "https://json-schema.org/draft/2020-12/schema",
    "type" : "object",
    "properties" : {
        "mylist" : {
            "type" : "array",
            "items" : {
                "type" : "string",
                "pattern" : "^[0-9]{13}$"
            },
            "minItems" : 1,
            "uniqueItems" : true
        }
    }
}

Java验证代码

jsonData 是字符串形式的 json 输入,inputSchema 是字符串形式的 json 模式
断言应该发现 2 个错误,但它发现零个。

ObjectMapper mapper = new ObjectMapper();
JsonSchemaFactory schemaFactory = 
JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
JsonNode node = mapper.readTree(jsonData);
JsonSchema schema = schemaFactory.getSchema(inputSchema);
Set<ValidationMessage> validationResult = schema.validate(node);

assertEquals(2, validationResult.size());

com.networknt:json-schema-validator有问题吗?

java json jsonschema json-schema-validator
1个回答
0
投票

使用最新版本的 json 模式验证器运行以下命令。

        String schemaData = "{\r\n"
                + "    \"$id\" : \"https://schema.mysite.se/myschema\",\r\n"
                + "    \"$schema\" : \"https://json-schema.org/draft/2020-12/schema\",\r\n"
                + "    \"type\" : \"object\",\r\n"
                + "    \"properties\" : {\r\n"
                + "        \"mylist\" : {\r\n"
                + "            \"type\" : \"array\",\r\n"
                + "            \"items\" : {\r\n"
                + "                \"type\" : \"string\",\r\n"
                + "                \"pattern\" : \"^[0-9]{13}$\"\r\n"
                + "            },\r\n"
                + "            \"minItems\" : 1,\r\n"
                + "            \"uniqueItems\" : true\r\n"
                + "        }\r\n"
                + "    }\r\n"
                + "}";
        
        String instanceData = "{\r\n"
                + "    \"mylist\": [\"123Abc\", \"123456789012\", \"1234567890123\"]\r\n"
                + "}";
        JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012);
        JsonSchema schema = factory.getSchema(schemaData);
        schema.validate(instanceData, InputFormat.JSON).forEach(System.out::println);

产生以下结果

$.mylist[0]: does not match the regex pattern ^[0-9]{13}$
$.mylist[1]: does not match the regex pattern ^[0-9]{13}$
© www.soinside.com 2019 - 2024. All rights reserved.