x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    JSON schema validation in Java

    Sometimes it is required to validate JSON objects before the processing as it helps in catching error early and to make sure valid data is received by application. You can validate a JSON object by providing JSON schema definition and then using it in Java.

    In this example we will show how to validate a JSON object using Java. We will use org.everit.json.schema library to validate JSON object. You can check list of JSON types that can be used by JSON schema here

    JSON Schema types

    First you need to download below dependencies


    Below is the JSON data & schema to validate the JSON

        "name":"Huge Grant",

        "$schema": "http://json-schema.org/draft-07/schema",
        "title" : "Person",
        "type": "object",
        "properties": {
            "id": {"type": "integer", "minLength": 4, "maxLength": 64},
            "name": {"type": "string"},
            "age": {"type": "integer", "minimum": 18},
            "profession": {"type": "string", "enum": ["Actor","Professor"]}
        "required": ["id", "name"]

    Validating JSON in Java

    Below example shows how to validate a JSON object in Java

    package json;
    import org.everit.json.schema.Schema;
    import org.everit.json.schema.ValidationException;
    import org.everit.json.schema.loader.SchemaLoader;
    import org.json.JSONObject;
    import org.json.JSONTokener;
    public class JsonValidator {
        public static void main(String[] args) {
            JSONObject jsonSchema = new JSONObject(new JSONTokener(
            JSONObject jsonData = new JSONObject(new JSONTokener(
            Schema schema = SchemaLoader.load(jsonSchema);
            try {
            } catch (ValidationException e) {
                System.out.println("schema validation failed");
            System.out.println("schema validated successfully");

    Console Output :

    schema validated successfully    

    Suppose you pass invalid value in json data "profession":"Actors" instead of "profession":"Actor", code will throw below Exception

    schema validation failed
    org.everit.json.schema.ValidationException: #/profession: Actors is not a valid enum value
    at org.everit.json.schema.ValidationException.prepend (ValidationException.java:333)
    at org.everit.json.schema.ValidationException.prepend (ValidationException.java:312)