Json схема валидации java

JSON Schema validation in Java

In this post we will see how to validate a JSON document against a JSON Schema in Java. We will use the same JSON document and Schema as in the previous post about JSON Schema.

You can find both as text files on GitHub: JSON document and JSON Schema.

We use the networknt JSON Schema validator library in this example. This library seems like a good fit because it supports the latest JSON Schema version (2019-09) and uses Jackson as JSON library. This makes it easy to integrate JSON Schema validation in Spring (hint: upcoming blog post).

We need to add the following dependency to our project:

Now we can validate our JSON document in Java:

When obtaining a JsonSchemaFactory we need to pass a VersionFlag. This defines the JSON Schema version we want to use (here: 2019-09).

We then use a small helper method to load both files from the classpath. A Jackson ObjectMapper instance is used to read the JSON data from the InputStream and parse it into a JsonNode object. From the JsonSchemaFactory we can obtain a JsonSchema object which can then be used validate the JsonNode. In case of validation errors the returned Set will contain one or more ValidationMessage objects. If the returned Set is empty, no validation errors were found.

Читайте также:  Java zip archive library

If we accidentally set the painting height to a negative number in our JSON document, we will get the following validation message:

You can find the example source code on GitHub.

Published on Java Code Geeks with permission by Michael Scharhag, partner at our JCG program. See the original article here: JSON Schema validation in Java

Источник

JSON Schema validation in Java

In this post we will see how to validate a JSON document against a JSON Schema in Java. We will use the same JSON document and Schema as in the previous post about JSON Schema.

You can find both as text files on GitHub: JSON document and JSON Schema.

We use the networknt JSON Schema validator library in this example. This library seems like a good fit because it supports the latest JSON Schema version (2019-09) and uses Jackson as JSON library. This makes it easy to integrate JSON Schema validation in Spring (hint: upcoming blog post).

We need to add the following dependency to our project:

 com.networknt json-schema-validator 1.0.42 

Now we can validate our JSON document in Java:

private static InputStream inputStreamFromClasspath(String path) < return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); >public static void main(String[] args) throws Exception < ObjectMapper objectMapper = new ObjectMapper(); JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909); try ( InputStream jsonStream = inputStreamFromClasspath("example.json"); InputStream schemaStream = inputStreamFromClasspath("example-schema.json") ) < JsonNode json = objectMapper.readTree(jsonStream); JsonSchema schema = schemaFactory.getSchema(schemaStream); SetvalidationResult = schema.validate(json); // print validation errors if (validationResult.isEmpty()) < System.out.println("no validation errors :-)"); >else < validationResult.forEach(vm ->System.out.println(vm.getMessage())); > > >

When obtaining a JsonSchemaFactory we need to pass a VersionFlag . This defines the JSON Schema version we want to use (here: 2019-09).

We then use a small helper method to load both files from the classpath. A Jackson ObjectMapper instance is used to read the JSON data from the InputStream and parse it into a JsonNode object. From the JsonSchemaFactory we can obtain a JsonSchema object which can then be used validate the JsonNode . In case of validation errors the returned Set will contain one or more ValidationMessage objects. If the returned Set is empty, no validation errors were found.

If we accidentally set the painting height to a negative number in our JSON document, we will get the following validation message:

$.dimension.height: must have a minimum value of 1

You can find the example source code on GitHub.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order

License

java-json-tools/json-schema-validator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

I pulled the additional text directly from #136 where @fge answered the question, "Do I need to abide by both licenses? Or can I pick which one to abide by?" Adding it here in the LICENSE file to help avoid a need for anyone else to dive into closed issues to find the answer.

Git stats

Files

Failed to load latest commit information.

README.md

The current version of this project is licensed under both LGPLv3 (or later) and ASL 2.0. The old version (2.0.x) was licensed under LGPL 3.0 (or later) only.

Version 2.2 is out. See here for the list of changes compared to 2.0. And of course, it still has all the features of older versions.

This is an implementation with complete validation support for the latest JSON Schema draft (v4, including hyperschema syntax support) and the previous draft (v3 — no hyperschema support though). Its list of features would be too long to enumerate here; please refer to the links above!

Should you wonder about it, this library is reported to work on Android. Starting with version 2.2.x, all APK conflicts have been resolved, so you can use this in this context as well.

This project has a dedicated Google group. For any questions you have about this software package, feel free to post! The author (me) will try and respond in a timely manner.

You can test this library online; this web site is in a project of its own, which you can fork and run by yourself.

  • current stable version: 2.2.14 (ChangeLog, Javadoc, code samples).
  • old stable version: 2.0.4 (ChangeLog, Javadoc, code samples).

This package is available on Maven central; the artifact is as follows:

dependencies < compile(group: "com.github.java-json-tools", name: "json-schema-validator", version: "2.2.14"); >
dependency> groupId>com.github.java-json-toolsgroupId> artifactId>json-schema-validatorartifactId> version>2.2.14version> dependency>

OUTDATED: Let me know if you need this in the issues section.

This jar contains the library plus all its dependencies. Download the lib jar (a little more than 6 MiB) from Bintray.

The versioning scheme is defined by the middle digit of the version number:

  • if this number is even, then this is the stable version; no new features will be added to such versions, and the user API will not change (save for some additions if requested).
  • if this number is odd, then this is the development version; new features will be added to those versions only, and the user API may change.

This implementation is based on the following drafts:

For a detailed discussion of the implementation, see here.

Please see the wiki for more details.

About

A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order

Источник

How to validate json schema in Java?¶

In this entry, we’ll consider typical problems that arise when you’re setting off parsing json with following validation. At the end of it, I’ll show how you can do it in concise and declarative fashion with Validol library.

Problems¶

Parsing JSON is usually a no-brainer. There are at least a couple of great libraries that do that: Jackson and GSON. The problem is that there seems to be no nice way to combine them with validation facility. That’s where the following problems unfold.

Validation is often an imperative code-clutter¶

Typically, json schema validation looks like a huge, highly temporally coupled sequence of imperative instructions. In library-independent java-like pseudo-code, it looks like the following:

JsonObject jsonObject = JSON.parse(request); if (!jsonObject.has("guest"))  return error("guest block is required"); > if (!jsonObject.get("guest").has("name"))  return error("guest name is required"); > String name = jsonObject.get("guest").get("name"); if (name.length > 70)  return error("guest name must be shorter than 70 characters"); > if (name.length  3)  return error("guest name must be at least 3 characters"); > if (!Pattern.compile("[a-Z]+").matcher(name).matches()  return error("guest name must contain only alpha characters"); > 

JSON Schema could be not so desirable to deal with¶

Those who want to break free from this imperative spaghetti hell often turn to quite complicated and intricate beast called JSON Schema. It’s a specification describing the structure and validation rules of json documents. Besides having a steep learning curve, it is a little bit too verbose. And things get worse quickly: JSON schema definition file grows twice as fast as the validated json itself.

Among the pluses, this format is a declarative one, which is a huge step forward comparing to the previous option. And there are couple of libraries supporting it.

Solution¶

Validol provides both parsing and validating capabilities, as well as solves both validation problems: it is declarative and concise.

Check out a quick example. Suppose we have a registration request. It has a couple of blocks, payment being one of them. For brevity sake, I’ll put only this one in the request:

 "payment": "expires_at":"12/29", "card_number":12345612341234 > > 

Here is how the actual validation code looks like:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
public class ValidatedRegistrationRequest implements ValidatableRegistrationRequest>  private String jsonRequestString; private Connection dbConnection; public ValidatedRegistrationRequest(String jsonRequestString, Connection dbConnection)  this.jsonRequestString = jsonRequestString; this.dbConnection = dbConnection; > @Override public ResultRegistrationRequest> result() throws Exception  return new FastFail<>( new WellFormedJson( new Unnamed<>(Either.right(new Present<>(this.jsonRequestString))) ), requestJsonObject -> new UnnamedBlocOfNameds<>( List.of( new FastFail<>( new IsJsonObject( new Required( new IndexedValue("payment", requestJsonObject) ) ), paymentJsonObject -> new NamedBlocOfNameds<>( "payment", List.of( new CardIsNotExpired( new AsString( new Required( new IndexedValue("expires_at", paymentJsonObject) ) ) ), new CardNumberIsNotBlacklisted( new CardNumberSatisfiesLuhnAlgorithm( new Required( new IndexedValue("card_number", paymentJsonObject) ) ), this.dbConnection ) ), Payment.class ) ) ), RegistrationRequest.class ) ) .result() ; > > 

Let’s see what’s going on here, line by line:

Line 6 Its constructor accepts not yet parsed json string. It might come from an incoming request, from received response, or from pretty much anywhere else.

Lines 16 : The higher-level validation object is FastFail block. If the first argument is invalid, an error is returned right away.

Lines 17-19 : json is checked whether it’s well-formed or not. If the latter, validation fails fast and returns a corresponding error.

Line 20 : if json is well-formed, a closure is invoked, and json data is passed as its single argument.

Line 21 : json data is validated. Its structure is an unnamed block of named blocks. It corresponds to a JSON Object.

Here is how a calling code looks when validation is successful:

ResultRegistrationRequest> result = new ValidatedRegistrationRequest(jsonRequestString).result(); result.isSuccessful(); result.value().raw().payment().cardNumber(); // 12345612341234 

Further reading¶

For more detailed example, check out Validol’s quick-start entry. Also, there are plenty of higher-level unit tests. And finally feel free to contribute!

Источник

Оцените статью