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

y0u0uwnf  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(194)

这可能是一个非常简单的事情,我错过了,但我的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(", ")) +"'");

字符串
但是'errors'是空的。在www.jsonschemavalidator.net上,这与预期的一样无效。
我忽略了什么?
谢谢你,谢谢

klr1opcd

klr1opcd1#

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);

字符串

相关问题