15

I’m building a REST API using Spring Boot and [jackson-module-jsonSchema] (https://github.com/FasterXML/jackson-module-jsonSchema) for JSON schema generation. I’m looking the best way to validate the request JSON payload arriving to my APIs endpoints (Spring controllers) against the defined JSON schema defined for the exposed resource, validation includes check required fields , format , min and max values, etc.. everything we can validate against the schema.

Seems jackson json schema module is useful for schema generation but not for validation, am I right? Any suggestion on how to achieve what I’m trying to do?

Alec
  • 217
  • 1
  • 3
  • 8

3 Answers3

15

If you take a look at JSON schema site, there are only two libraries for validation in Java.

  1. The one that Jorge Campos suggested is mature, but looking for new maintainer: https://github.com/fge/json-schema-validator
  2. Second one is relatively new: http://github.com/everit-org/json-schema

I was recently in situation where I had to choose one or the other and I picked first option. It is being used also by Rest Assured library under the hood.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
luboskrnac
  • 23,973
  • 10
  • 81
  • 92
  • thanks for your answer @luboskrnac I tried https://github.com/fge/json-schema-validator and is looking good, when testing it I realized that jackson is generating JSON schema v3 and validator is exepcting v4-draft, I'm considering to change Jackson for other library , do you have any suggestion? – Alec Jan 19 '16 at 14:40
  • 2
    mJson also fully supports schema validation and it's much simpler to use than the above: http://bolerio.github.io/mjson/ – user252690 Mar 31 '16 at 14:43
  • 1
    Please note that now is only one library is recommended: http://json-schema.org/implementations.html#validators – sinner Dec 18 '18 at 08:35
2

You can also look at Rest Assured Json Schema validator

https://www.baeldung.com/rest-assured-json-schema

  • Please give some explanation to the content of a link answer. – Israel dela Cruz Jul 09 '19 at 01:48
  • @IsraeldelaCruz The idea here is to define json schema in your classpath and then validate the response against this schema using json validator. something like this assertThat().body(matchesJsonSchemaInClasspath("event_0.json")) You can go through the example on the link and let me know if you still have any questions. – Ankush Puri Jan 21 '20 at 22:05
0

As of 2023, the following JSON schema validator library seems to be a good fit: https://github.com/networknt/json-schema-validator

This is a Java implementation of the JSON Schema Core Draft v4, v6, v7, v2019-09 and v2020-12(partial) specification for JSON schema validation. In addition, it also works for OpenAPI 3.0 request/response validation with some configuration flags.

And there is one more validator library which looks promising but YMMV: https://github.com/openapi-processor/openapi-parser

Saikat
  • 14,222
  • 20
  • 104
  • 125