Giter Site home page Giter Site logo

zhouyuchina / json-schema-validator Goto Github PK

View Code? Open in Web Editor NEW

This project forked from networknt/json-schema-validator

0.0 0.0 0.0 2.18 MB

A fast Java JSON schema validator that supports draft V4, V6, V7, V2019-09 and V2020-12

License: Apache License 2.0

Python 2.12% Java 97.88%

json-schema-validator's Introduction

Stack Overflow | Google Group | Gitter Chat | Subreddit | Youtube | Documentation | Contribution Guide |

CI Maven Central codecov.io Javadocs

This is a Java implementation of the JSON Schema Core Draft v4, v6, v7, v2019-09 and v2020-12 specification for JSON schema validation.

In addition, it also works for OpenAPI 3.0 request/response validation with some configuration flags. For users who want to collect information from a JSON node based on the schema, the walkers can help. The default JSON parser is the Jackson that is the most popular one. As it is a key component in our light-4j microservices framework to validate request/response against OpenAPI specification for light-rest-4j and RPC schema for light-hybrid-4j at runtime, performance is the most important aspect in the design.

JSON Schema Draft Specification Compatibility

Information on the compatibility support for each version, including known issues, can be found in the Compatibility with JSON Schema versions document.

Upgrading to new versions

Information on notable or breaking changes when upgrading the library can be found in the Upgrading to new versions document. This library can contain breaking changes in minor version releases.

For the latest version, please check the Releases page.

Why this library

Performance

It is the fastest Java JSON Schema Validator as far as I know. Here is the testing result compare with the other two open-source implementations. It is about 32 times faster than the Fge and five times faster than the Everit.

  • fge: 7130ms
  • everit-org: 1168ms
  • networknt: 223ms

You can run the performance tests for three libraries from https://github.com/networknt/json-schema-validator-perftest

Parser

It uses Jackson that is the most popular JSON parser in Java. If you are using Jackson parser already in your project, it is natural to choose this library over others for schema validation.

YAML Support

The library works with JSON and YAML on both schema definitions and input data.

OpenAPI Support

The OpenAPI 3.0 specification is using JSON schema to validate the request/response, but there are some differences. With a configuration file, you can enable the library to work with OpenAPI 3.0 validation.

Dependency

Following the design principle of the Light Platform, this library has minimum dependencies to ensure there are no dependency conflicts when using it.

The following are the dependencies that will automatically be included when this library is included.

<dependency>
    <!-- Used for logging -->
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${version.slf4j}</version>
</dependency>

<dependency>
    <!-- Used to process JSON -->
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${version.jackson}</version>
</dependency>

<dependency>
    <!-- Used to process YAML -->
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>${version.jackson}</version>
</dependency>

<dependency>
    <!-- Used to validate RFC 3339 date and date-time -->
    <groupId>com.ethlo.time</groupId>
    <artifactId>itu</artifactId>
    <version>${version.itu}</version>
</dependency>

The following are the optional dependencies that may be required for certain options.

These are not automatically included and setting the relevant option without adding the library will result in a ClassNotFoundException.

<!-- This is required when setting setEcma262Validator(true)  -->
<dependency>
    <!-- Used to validate ECMA 262 regular expressions -->
    <groupId>org.jruby.joni</groupId>
    <artifactId>joni</artifactId>
    <version>${version.joni}</version>
    <optional>true</optional>
</dependency>

The YAML dependency can be excluded if this is not required. Attempting to process schemas or input that are YAML will result in a ClassNotFoundException.

<dependency>
    <groupId>com.networknt</groupId>
    <artifactId>json-schema-validator</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Community

This library is very active with a lot of contributors. New features and bug fixes are handled quickly by the team members. Because it is an essential dependency of the light-4j framework in the same GitHub organization, it will be evolved and maintained along with the framework.

Prerequisite

The library supports Java 8 and up. If you want to build from the source code, you need to install JDK 8 locally. To support multiple version of JDK, you can use SDKMAN

Usage

Adding the dependency

This package is available on Maven central.

Maven:

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

Gradle:

dependencies {
    implementation(group: 'com.networknt', name: 'json-schema-validator', version: '1.2.0');
}

Validating inputs against a schema

The following example demonstrates how inputs is validated against a schema. It comprises the following steps.

  • Creating a schema factory with the default schema dialect and how the schemas can be retrieved.
    • Configuring mapping the $id to a retrieval URI using schemaMappers.
    • Configuring how the schemas are loaded using the retrieval URI using schemaLoaders. For instance a Map<String, String> schemas containing a mapping of retrieval URI to schema data as a String can by configured using builder.schemaLoaders(schemaLoaders -> schemaLoaders.schemas(schemas)). This also accepts a Function<String, String> schemaRetrievalFunction.
  • Creating a configuration for controlling validator behavior.
  • Loading a schema from a schema location along with the validator configuration.
  • Using the schema to validate the data along with setting any execution specific configuration like for instance the locale or whether format assertions are enabled.
// This creates a schema factory that will use Draft 2012-12 as the default if $schema is not specified in the schema data. If $schema is specified in the schema data then that schema dialect will be used instead and this version is ignored.
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.getInstance(VersionFlag.V202012, builder -> 
    // This creates a mapping from $id which starts with https://www.example.org/ to the retrieval URI classpath:schema/
    builder.schemaMappers(schemaMappers -> schemaMappers.mapPrefix("https://www.example.org/", "classpath:schema/"))
);

SchemaValidatorsConfig config = new SchemaValidatorsConfig();
// By default JSON Path is used for reporting the instance location and evaluation path
config.setPathType(PathType.JSON_POINTER);
// By default the JDK regular expression implementation which is not ECMA 262 compliant is used
// Note that setting this to true requires including the optional joni dependency
// config.setEcma262Validator(true);

// Due to the mapping the schema will be retrieved from the classpath at classpath:schema/example-main.json. If the schema data does not specify an $id the absolute IRI of the schema location will be used as the $id.
JsonSchema schema = jsonSchemaFactory.getSchema(SchemaLocation.of("https://www.example.org/example-main.json"), config);
String input = "{\r\n"
    + "  \"main\": {\r\n"
    + "    \"common\": {\r\n"
    + "      \"field\": \"invalidfield\"\r\n"
    + "    }\r\n"
    + "  }\r\n"
    + "}";

Set<ValidationMessage> assertions = schema.validate(input, InputFormat.JSON, executionContext -> {
    // By default since Draft 2019-09 the format keyword only generates annotations and not assertions
    executionContext.getConfig().setFormatAssertionsEnabled(true);
});

Validating a schema against a meta schema

The following example demonstrates how a schema is validated against a meta schema.

This is actually the same as validating inputs against a schema except in this case the input is the schema and the schema used is the meta schema.

JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.getInstance(VersionFlag.V202012, builder -> 
    // This creates a mapping to load the meta schema from the library classpath instead of remotely
    // This is better for performance and the remote may choose not to service the request
    // For instance Cloudflare will block requests that have older Java User-Agent strings eg. Java/1.
    builder.schemaMappers(schemaMappers -> 
        schemaMappers.mapPrefix("https://json-schema.org", "classpath:").mapPrefix("http://json-schema.org", "classpath:"))
);

SchemaValidatorsConfig config = new SchemaValidatorsConfig();
// By default JSON Path is used for reporting the instance location and evaluation path
config.setPathType(PathType.JSON_POINTER);
// By default the JDK regular expression implementation which is not ECMA 262 compliant is used
// Note that setting this to true requires including the optional joni dependency
// config.setEcma262Validator(true);

// Due to the mapping the meta schema will be retrieved from the classpath at classpath:draft/2020-12/schema.
JsonSchema schema = jsonSchemaFactory.getSchema(SchemaLocation.of(SchemaId.V202012), config);
String input = "{  \n"
    + "  \"type\": \"object\",  \n"
    + "  \"properties\": {    \n"
    + "    \"key\": { \n"
    + "      \"title\" : \"My key\", \n"
    + "      \"type\": \"invalidtype\" \n"
    + "    } \n"
    + "  }\n"
    + "}";
Set<ValidationMessage> assertions = schema.validate(input, InputFormat.JSON, executionContext -> {
    // By default since Draft 2019-09 the format keyword only generates annotations and not assertions
    executionContext.getConfig().setFormatAssertionsEnabled(true);
});

Projects

The light-rest-4j, light-graphql-4j and light-hybrid-4j use this library to validate the request and response based on the specifications. If you are using other frameworks like Spring Boot, you can use the OpenApiValidator, a generic OpenAPI 3.0 validator based on the OpenAPI 3.0 specification.

If you have a project using this library, please submit a PR to add your project below.

Contributors

Thanks to the following people who have contributed to this project. If you are using this library, please consider to be a sponsor for one of the contributors.

@stevehu

@prashanth-chaitanya

@fdutton

@valfirst

@BalloonWen

@jiachen1120

@ddobrin

@eskabetxe

@ehrmann

@prashanthjos

@Subhajitdas298

@FWiesner

@rhwood

@jawaff

@nitin1891

For all contributors, please visit https://github.com/networknt/json-schema-validator/graphs/contributors

If you are a contributor, please join the GitHub Sponsors and switch the link to your sponsors dashboard via a PR.

Sponsors

Individual Sponsors

Corporation Sponsors

json-schema-validator's People

Contributors

andreasaloew avatar anjnerajat avatar aznan2 avatar balloonwen avatar bartoszm avatar chrisken avatar costas80 avatar ddobrin avatar dependabot[bot] avatar dreis2211 avatar ehrmann avatar eskabetxe avatar fdutton avatar fwiesner avatar gavinchenyan avatar jawaff avatar jiachen1120 avatar jorgesartori avatar justin-tay avatar kosty avatar nicholasazar avatar nitin1891 avatar olegshtch avatar prashanth-chaitanya avatar prashanthjos avatar rhwood avatar stevehu avatar subhajitdas298 avatar valfirst avatar vmaurin avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.