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
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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With