How to validate a json schema against the version spec it specifies in Java

后端 未结 1 456
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 08:54

Given a json schema like this..


    {
   \"$schema\": \"http://json-schema.org/draft-04/schema#\",
   \"title\": \"Product\",
   \"description\": \"A product from Ac         


        
相关标签:
1条回答
  • 2021-01-25 09:25

    The schema linked from every JSON schema is in fact a sort of "meta-schema" for JSON schemas, so you can in fact use it to validate a schema as you suggest.

    Suppose we have saved the meta-schema as a file called meta-schema.json, and our potential schema as schema.json. First we need a way to load these files as JSONObjects:

    public static JSONObject loadJsonFromFile(String fileName) throws FileNotFoundException {
        Reader reader = new FileReader(fileName);
        return new JSONObject(new JSONTokener(reader));
    }
    

    We can load the meta-schema, and load it into the json-schema library you linked:

    JSONObject metaSchemaJson = loadJsonFromFile("meta-schema.json");
    Schema metaSchema = SchemaLoader.load(metaSchemaJson);
    

    Finally, we load the potential schema and validate it using the meta-schema:

    JSONObject schemaJson = loadJsonFromFile("schema.json");
    try {
        metaSchema.validate(schemaJson);
        System.out.println("Schema is valid!");
    } catch (ValidationException e) {
        System.out.println("Schema is invalid! " + e.getMessage());
    }
    

    Given the example you posted, this prints "Schema is valid!". But if we were to introduce an error, for example by changing the "type" of the "name" field to "foo" instead of "string", we would get the following error:

    Schema is invalid! #/properties/name/type: #: no subschema matched out of the total 2 subschemas
    
    0 讨论(0)
提交回复
热议问题