1
votes

I have written a JSON Schema by 2019-09 (https://json-schema.org/draft/2019-09/release-notes.html). How can I validate it using java?

I want to write the method (throw Exception if validation fails):

void validate(Path pathToSchema) throws Exception {
   // validation of schema by pathToSchema
}

P.S. I want to validate the JSON Schema for correctness, not JSON Document by JSON Schema.

2
This is the only known JSON Schema implementation for Java that supports draft 2019-09 github.com/ssilverman/snowy-jsonJason Desrosiers

2 Answers

0
votes

You do something like this with the well known networknt lib:

    JsonSchema schema = null;
    JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V201909);
    try {
      schema = factory.getSchema(
          "{\n"
              + "  \"$schema\": \"http://json-schema.org/draft/2019-09/schema\",\n"
              + "  \"$id\": \"#MyJsonClassSchema.json\",\n"
              + "  \"type\": \"object\",\n"
              + "  \"properties\": {\n"
              + "    \"myProperty\": {\n"
              + "      \"type\": \"string\"\n"
              + "    }\n"
              + "  }\n"
              + "}"
      );
    } catch (JsonSchemaException e) {
      System.out.println("json schema invalid: \n" + e);
    }
    return schema;

This will validate some features of the json-schema starting with the schema version you set in your input.

-1
votes

You can use the Json validator: - https://github.com/fge/json-schema-validator

Or you can simply try to parse the Json using Google Gson and catch syntax exception to validate it like below :-

try{
JsonParser parser = new JsonParser();
parser.parse(passed_json_string);
} 
catch(JsonSyntaxException jse){
System.out.println("Not a valid Json String:"+jse.getMessage());
}