Introduction to JSON Schema in Java – Java中的JSON模式介绍

最后修改: 2016年 7月 8日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

JSON Schema is a declarative language for validating the format and structure of a JSON Object. It allows us to specify the number of special primitives to describe exactly what a valid JSON Object will look like.

JSON Schema是一种声明性语言,用于验证JSON对象的格式和结构。它允许我们指定一些特殊的基元来准确描述一个有效的JSON对象的样子。

The JSON Schema specification is divided into three parts:

JSON Schema规范分为三个部分。

  • JSON Schema Core: The JSON Schema Core specification is where the terminology for a schema is defined.
  • JSON Schema Validation: The JSON Schema Validation specification is the document that defines the valid ways to define validation constraints. This document also defines a set of keywords that can be used to specify validations for a JSON API. In the examples that follow, we’ll be using some of these keywords.
  • JSON Hyper-Schema: This is another extension of the JSON Schema spec, wherein, the hyperlink and hypermedia-related keywords are defined.

2. Defining a JSON Schema

2.定义一个JSON模式

Now that we have defined what a JSON Schema is used for, let’s create a JSON Object and the corresponding JSON Schema describing it.

现在我们已经定义了JSON Schema的用途,让我们创建一个JSON对象和描述它的相应的JSON Schema

The following is a simple JSON Object representing a product catalog:

下面是一个简单的JSON对象,代表一个产品目录。

{
    "id": 1,
    "name": "Lampshade",
    "price": 0
}

We could define its JSON Schema as follow:

我们可以定义其JSON模式如下。

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Product",
    "description": "A product from the catalog",
    "type": "object",
    "properties": {
        "id": {
            "description": "The unique identifier for a product",
            "type": "integer"
        },
        "name": {
            "description": "Name of the product",
            "type": "string"
        },
        "price": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        }
    },
    "required": ["id", "name", "price"]
}

As we can see a JSON Schema is a JSON document, and that document MUST be an object. Object members (or properties) defined by JSON Schema are called keywords.

我们可以看到,JSON Schema是一个JSON文档,而该文档必须是一个对象。由JSON Schema定义的对象成员(或属性)被称为keywords

Let’s explain the keywords that we have used in our sample:

让我们解释一下我们在样本中使用的关键词。

  • The $schema keyword states that this schema is written according to the draft v4 specification.
  • The title and description keywords are descriptive only, in that they do not add constraints to the data being validated. The intent of the schema is stated with these two keywords: describes a product.
  • The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.

Also, a JSON Schema MAY contain properties which are not schema keywords. In our case id, name, price will be members (or properties) of the JSON Object.

另外,JSON模式可能包含不是模式关键字的属性。在我们的例子中,id, name, price将成为JSON Object的成员(或属性)。

For each property, we can define the type. We defined id and name as string and price as number. In JSON Schema a number can have a minimum. By default this minimum is inclusive, so we need to specify exclusiveMinimum.

对于每个属性,我们可以定义type。我们把idname定义为string,把price定义为number。在JSON Schema中,一个数字可以有一个最小值。默认情况下,这个最小值是包含的,所以我们需要指定exclusiveMinimum

Finally, the Schema tells that id, name, and price are required.

最后,Schema告诉我们idnamepricerequired

3. Validation With JSON Schema

3.用JSON模式进行验证

With our JSON Schema put in place we can validate our JSON Object.

有了我们的JSON Schema我们可以验证我们的JSON对象

There are many libraries to accomplish this task. For our example, we have chosen the Java json-schema library.

有许多来完成这项任务。在我们的例子中,我们选择了Java的json-schema库。

First of all, we need to add the following dependency to our pom.xml:

首先,我们需要在我们的pom.xml中添加以下依赖关系。

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>1.0.72</version>
</dependency>

Finally, we can write a couple of simple test case to validate our JSON Object:

最后,我们可以写几个简单的测试案例来验证我们的JSON对象:

@Test
public void givenInvalidInput_whenValidating_thenInvalid() throws IOException {
    JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
    JsonSchema jsonSchema = factory.getSchema(
     JSONSchemaUnitTest.class.getResourceAsStream("/schema.json"));
    JsonNode jsonNode = mapper.readTree(
     JSONSchemaUnitTest.class.getResourceAsStream("/product_invalid.json"));
    Set<ValidationMessage> errors = jsonSchema.validate(jsonNode);
    assertThat(errors).isNotEmpty().asString().contains("price: must have a minimum value of 0");
}

In this case, validation error will be received.

在这种情况下,将收到验证错误

The second test looks like the following:

第二个测试看起来像下面这样。

@Test 
public void givenValidInput_whenValidating_thenValid() throws ValidationException { 
    JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4); 
    JsonSchema jsonSchema = factory.getSchema( 
     JSONSchemaUnitTest.class.getResourceAsStream("/schema.json")); 
    JsonNode jsonNode = mapper.readTree( 
     JSONSchemaUnitTest.class.getResourceAsStream("/product_valid.json")); 
    Set<ValidationMessage> errors = jsonSchema.validate(jsonNode); 
    assertThat(errors).isEmpty(); 
}

Since we use a valid JSON Object, no validation error will be thrown.

由于我们使用了有效的JSON对象,所以不会出现验证错误。

4. Conclusion

4.结论

In this article, we have defined what a JSON Schema is and which are some relevant keyword that helps us to define our schema.

在这篇文章中,我们已经定义了什么是JSON模式,以及哪些是一些相关的关键词帮助我们定义我们的模式。

Coupling a JSON Schema with its corresponding JSON Object representation we can perform some validation task.

将一个JSON Schema与其对应的JSON Object表示相耦合,我们可以执行一些验证任务。

A simple test case of this article can be found in the GitHub project.

本文的一个简单测试案例可以在GitHub项目中找到。