JSON Schema Support using Jackson in Java?


JSON Schema is a specification for JSON based format for defining the structure of JSON data. The JsonSchema class can provide a contract for what JSON data is required for a given application and how to interact with it. The JsonSchema can define validation, documentation, hyperlink navigation, and interaction control of JSON data. We can generate the JSON schema using the generateSchema() method of JsonSchemaGenerator, this class wraps the JSON schema generation functionality.

Syntax

public JsonSchema generateSchema(Class<T> type) throws com.fasterxml.jackson.databind.JsonMappingException

Example

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import java.util.List;
public class JSONSchemaTest {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper jacksonObjectMapper = new ObjectMapper();
      JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(jacksonObjectMapper);
      JsonSchema schema = schemaGen.generateSchema(Person.class);
      String schemaString = jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
      System.out.println(schemaString);
   }
}
// Person class
class Person {
   private String name;
   private int age;
   private List<String> courses;
   private Address address;
   public String getName() {
      return name;
   }
   public int getAge(){
      return age;
   }
   public List<String> getCourse() {
      return courses;
   }
   public Address getAddress() {
      return address;
   }
}
// Address class
class Address {
   private String firstLine;
   private String secondLine;
   private String thirdLine;
   public String getFirstLine() {
      return firstLine;
   }
   public String getSecondLine() {
      return secondLine;
   }
   public String getThirdLine() {
      return thirdLine;
   }
}

Output

{
   "type" : "object",
   "id" : "urn:jsonschema:Person",
   "properties" : {
      "name" : {
         "type" : "string"
      },
      "age" : {
         "type" : "integer"
      },
      "address" : {
         "type" : "object",
         "id" : "urn:jsonschema:Address",
         "properties" : {
            "firstLine" : {
               "type" : "string"
            },
            "secondLine" : {
               "type" : "string"
            },
            "thirdLine" : {
               "type" : "string"
            }
         }
      },
      "course" : {
         "type" : "array",
         "items" : {
            "type" : "string"
         }
      }
   }
}

Updated on: 08-Jul-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements