如何使用networknt/json-schema-validator验证数组项类型?

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

这可能是我缺少的一件非常简单的事情,但是我的 json-schema-validator (networknt/json-schema-validator) 不会验证数组中项目的类型。

这个 Java 片段应该会产生错误:

var schema = "{\n" +
                    "  \"$schema\": \"http://json-schema.org/draft/2020-12/schema#\",\n" +
                    "  \"type\": \"array\",\n" +
                    "  \"items\": [\n" +
                    "    {\n" +
                    "      \"type\": \"integer\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";

var input = "[true,false,{},\"foo\"]";

var factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
var jSchema = factory.getSchema(schema);
var errors = jSchema.validate(new ObjectMapper().readTree(input));
System.out.println("Errors: '"+errors.stream().map(ValidationMessage::getMessage).collect(joining(", ")) +"'");

但是'错误是空的。在 www.jsonschemavalidator.net 上,这按预期无效。

我在这里忽略了什么明显的东西?

谢谢!

java json-schema-validator light-4j
1个回答
0
投票
    JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);

    SchemaValidatorsConfig schemaValidatorsConfig = new SchemaValidatorsConfig ();

    //schemaValidatorsConfig.setFailFast(true);
    schemaValidatorsConfig.setHandleNullableField(true);
    schemaValidatorsConfig.setTypeLoose(false);

    //build json schema node
    JsonNode schemaNode;
    try {
        schemaNode = objectMapper.valueToTree(schema);
        
    } catch (Exception e) {
        
    }
    
    //build input json node
    JsonNode jsonNode;
    try {
        jsonNode = objectMapper.readTree(json);
    } catch (IOException e) {
        
    }
    
    //validate the json with the schema
    Set<ValidationMessage> validationErrors;
    
    JsonSchema jsonSchema = jsonSchemaFactory.getSchema(schemaNode, schemaValidatorsConfig);
    
    validationErrors = jsonSchema.validate(jsonNode);
© www.soinside.com 2019 - 2024. All rights reserved.