Skip to content

Example for schema written in YAML and files to validate in JSON #1150

Closed
@hasant73

Description

@hasant73

Hi there,

I have a quite complicated schema from my customer with a lot of references inside and I'm struggling to find a library that works with it.
Could you please give a example that accepts a YAML file as a schema and a JSON file as data to be validated.

My code looks like this so far:

ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
Object obj = yamlReader.readValue(openAPIFile, Object.class);
ObjectMapper jsonWriter = new ObjectMapper();
String jsonSchemaStr = jsonWriter.writeValueAsString(obj);

ObjectMapper jsonReader = new ObjectMapper();
JsonNode node = jsonReader.readValue(inputFile, JsonNode.class);

// convert the schemas to json
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema jsonSchema = factory.getSchema(jsonSchemaStr);
Set<ValidationMessage> validationMessage = jsonSchema.validate(node);
for (ValidationMessage v : validationMessage) {
  LOGGER.error(v.toString());
}
if (!validationMessage.isEmpty()) {
  throw new RuntimeException("Validation error");
}

Thanks you

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions