How to validate array item types with networknt/json-schema-validator?

487 views Asked by At

its probably a very simple thing that Im missing, but my json-schema-validator (networknt/json-schema-validator) doesnt validate the type of my items inside an array.

This Java-snippet should yield errors:

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(", ")) +"'");

but 'errors is empty. Over on www.jsonschemavalidator.net this is invalid as expected.

What obvious am I overlooking here ?

Thanks!

1

There are 1 answers

0
Marian On
    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);