Java JsonSchema-class And Method Code Example


Here is an example of how to use the JsonSchema class from the com.fasterxml.jackson.databind package in the Jackson library to generate a JSON schema from a Java class:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsonschema.JsonSchema;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Example {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode schemaNode = mapper.createObjectNode();
        JsonSchema jsonSchema = mapper.generateJsonSchema(MyClass.class);
        ((ObjectNode) schemaNode).set("mySchema", jsonSchema.getSchemaNode());

        // Print the JSON schema
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schemaNode));
    }
}

This example uses the generateJsonSchema method of the ObjectMapper class to generate a JsonSchema instance for the MyClass class. It then uses the getSchemaNode method of the JsonSchema class to get the JSON node representation of the schema, which can be printed or written to a file.

Note that you need to have jackson-module-jsonSchema library on classpath

<dependency>
  <groupId>com.fasterxml.jackson.module</groupId>
  <artifactId>jackson-module-jsonSchema</artifactId>
  <version>2.11.2</version>
</dependency>