Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include Bean Validation constraints in Jackson generated JSON schema

I am using Jersey 1.2 (still using JDK 1.5) and have developed a REST Booking Web Resource and an associated Booking POJO.

I have used Bean Validation to restrict the size/type of the fields e.g.

@NotNull
@Size(message="invalid size",min=3,max=20)
@Pattern(message="invalid pattern",regexp = "^[A-Za-z]*")
@JsonProperty(value = "forename")
private String forename;

and have used the Jackson ObjectMapper.generateJsonSchema class to generate the JSON schema however this ignores all the validation annotations so I just get:

"forename" : {
  "type" : "string"
}

Is there any way to include the restriction information as part of the generated schema?

Many thanks

like image 310
MandyW Avatar asked Jan 03 '13 12:01

MandyW


People also ask

How do you validate a JSON Schema?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

What is Bean Validation constraints?

The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined. User-defined constraints are called custom constraints.

How do you validate a schema in Rest assured?

Once we launch this application, we shall get a field called the Sample JSON Document. Here, we have to add the JSON body whose scheme we want to validate. Then click on the Generate Schema button. Then the corresponding scheme for the JSON gets generated at the bottom of the page.


2 Answers

Looks like jackson-module-jsonSchema 2.5.0+ now supports some of the annotations now:

ValidationSchemaFactoryWrapper personVisitor = new    
ValidationSchemaFactoryWrapper();
ObjectMapper mapper = new ObjectMapper();
mapper.acceptJsonFormatVisitor(Person.class, personVisitor);
JsonSchema personSchema = personVisitor.finalSchema();
like image 61
indybee Avatar answered Oct 12 '22 23:10

indybee


There is no way to do that out-of-the-box, but this extension module:

https://github.com/FasterXML/jackson-module-jsonSchema

should let you modify Schema Generator in a way to add whatever extra information you want. Caveat: this is a new project and probably requires you to use 2.2.0-SNAPSHOT version of core Jackson components.

like image 43
StaxMan Avatar answered Oct 12 '22 22:10

StaxMan