How to validate JSON schema structure with another JSON schema with Java?

Viewed 1237

I need to validate JSON schema structure with referenced JSON schema. I need to make sure that JSON schema adhere reference structure.

Example - Below JSON schema uses reference of "$schema": "https://json-schema.org/draft/2020-12/schema" . I need to make sure that below Json schema is valid against "$schema": "https://json-schema.org/draft/2020-12/schema"

I haven't found any Java SDK/library yet to validate one schema against another json schema. It will be great if anyone can provide any input to validate Json schema against another json schema

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://test.com/employee.schema.json",
  "title": "employee",
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string",
      "description": "The employee's first name."
    },
    "lastName": {
      "type": "string",
      "description": "The employee's last name."
    },
    "age": {
      "description": "Age",
      "type": "integer",
      "minimum": 0
    }
  }
}
3 Answers

If your evaluator can accept a URI as the schema, then just use "https://json-schema.org/draft/2020-12/schema", and your schema as the input data.

Evaluators should be able to accept URIs of "known" schemas, that have been preloaded ahead of time, and if your implementation supports this version of the specification, then it should know what to do with that URI.

FWIW, your schema is valid.

I did something similar sometimes back to an enterprise project, with lot of my research over internet, I end up using following library.

https://github.com/everit-org/json-schema

I am not sure if it works with the version you specified, when i used it, it was very much compatible with draft-07.

Following are the sample code snippet for loading an schema & validating a json with it.

// Load your schema, named as mySchema    
SchemaLoader loader = SchemaLoader.builder()
                .schemaJson(mySchema)
                .build();
Schema schema = loader.load().build();

// Validate input json with loaded schema
try {
  schema.validate(input);
} catch (ValidationException e) {
 // Error occurred while validating the schema
}

I wrote one more answer to similar question on how to handle different custom errors thrown in the validation.

How to customize error messages for JSONSchema?

Hope this helps, Let me know if you need any further clarification.

We had requirement to validate schema with most stable schemas such as - 2020-12, 2019-09, draft-07,-06, etc., And validate example JSON messages with custom schema as well.

Tested with couple of libraries, and found jsonschemafriend library is best fit for our requirement.

Sample code to validate one JSON schema with another Json Schema - Refer JsonSchemaFriendValidator.java for more samples such as - JSON message validation against JSON Schema

import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.jimblackler.jsonschemafriend.Schema;
import net.jimblackler.jsonschemafriend.SchemaStore;
import net.jimblackler.jsonschemafriend.Validator;

public class TestSchema {

    @Test
    public void testCustomSchema_2019_09_Valid() throws Exception {

        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("json-validation-poc/test-custom-schema-2019-09-valid.json");
        String schemaAsJson = IOUtils.toString(resourceAsStream, Charset.defaultCharset());

        JsonObject schemaJsonObject = JsonParser.parseString(schemaAsJson).getAsJsonObject();
        String schemaUriRef = schemaJsonObject.get("$schema").getAsString();

        SchemaStore schemaStore = new SchemaStore(); // Initialize a SchemaStore.
        Schema schema = schemaStore.loadSchema(new URI(schemaUriRef));

        Validator validator = new Validator();
        validator.validateJson(schema, schemaAsJson); // Throw Validation exception for failure1`
    }
}
Related