I need to validate that a property is a valid JSON schema. In the following example, I need to validate the payload
property:
message:
name: userSignedUp
version: 1.0.0
payload:
name:
type: string
timestamp:
type: string
warningLevel:
type: string
enum:
- HIGH
- MEDIUM
- LOW
This is my json-schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Message",
"properties": {
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"payload": {
"$ref": "#/definitions/schema"
},
},
"definitions":{
"schema": {
# --> How should the schema be defined?
},
"required":[
"name",
"version",
"payload"
]
}
To my understanding, I need to use Core/Validation Dialect meta-schema. I didn't really understand how to do so, because simply copying the json-meta schema is not clear - what should I replace meta/*
with? Is that how the definition should look like?
How should my schema
definition should be defined?
Thanks
So I ended up using the everit-json-schema
library, I created a local copy of the draft-07 Core schema meta-schema
, loaded it using the library and then validated my schemas against it.
private static Schema META_SCHEMA_VALIDATOR;
static {
JSONObject metaSchema;
try {
metaSchema = new JSONObject((Files.readAllBytes(Paths.get("src/main/resources/meta-schema.json"))));
} catch (Exception ex) {
throw new RuntimeException("Failed reading metaschema file");
}
var schemaLoader = SchemaLoader
.builder()
.schemaJson(metaSchema)
.draftV7Support()
.build();
META_SCHEMA_VALIDATOR = schemaLoader.load().build();
}
...
...
private void validateSchema(Payload schema) {
var schemaString = new Gson().toJson(schema.getAdditionalProperties(), Map.class);
var schemaJson = new JSONObject(schemaString);
try {
META_SCHEMA_VALIDATOR.validate(schemaJson);
} catch (Exception ex) {
throw new InvalidSpecException(String.format("Schema validation failed for schema: `%s`, ex: `%s`", schemaString, ex.getMessage()));
}
}