Java JSON Tutorial - JSON Schema








Like XML schema, JSON data format also has Schema, which is a specification for JSON based format.

JSON Schema is also written in JSON format. It is used to validate JSON data.

JSON Schema Example

The following code shows a basic JSON schema.

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Book",
    "description": "A book from Java2s.com",
    "type": "object",
    "properties": {
        "id": {
            "description": "ID for JSON",
            "type": "integer"
        },
        "name": {
            "description": "Name for JSON",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        }
    },
    "required": ["id", "name", "price"]
}

$schema states that this schema is written according to the draft v4 specification.

title keyword sets the title to your schema.

description field is for the description of the schema.

type keyword defines the first constraint on our JSON data.

properties defines various keys and their value types, minimum and maximum values to be used in JSON file.

required marks the required properties.

minimum is the constraint on the value and represents minimum acceptable value.

exclusiveMinimum true marks that the value should be greater than the value of 'minimum'.

maximum is the constraint on the value and represents maximum acceptable value.

exclusiveMaximum true value marks that the value should be lower than the value of "maximum".

multipleOf specifies that a numeric instance is valid if the result of the division of the instance by this keyword's value is an integer.

maxLength sets the max length of a string.

minLength sets min length of a string.

pattern field specifies the regular expression that matches value.

http://json-schema.org has the complete list of keywords which can be used in defining JSON schema.