Created
October 9, 2019 13:02
-
-
Save kouzouigh/908abad81d2c60ef374c50e02c1e0e25 to your computer and use it in GitHub Desktop.
Writing Json Schema with Bean Validation Constraints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.module.jsonSchema.JsonSchema; | |
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator; | |
import com.fasterxml.jackson.module.jsonSchema.customProperties.ValidationSchemaFactoryWrapper; | |
import lombok.Data; | |
@Data | |
class MyClass { | |
@Size(min=14, max=14) | |
private String reference; | |
@Pattern(regexp = "^\\d{5}$") | |
private String codeBank; | |
} | |
public static void main(String[] args) throws Exception { | |
ObjectMapper mapper = new ObjectMapper(); | |
ValidationSchemaFactoryWrapper visitor = new ValidationSchemaFactoryWrapper(); | |
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper); | |
mapper.acceptJsonFormatVisitor(MyClass.class, visitor); | |
JsonSchema jsonSchema = visitor.finalSchema(); | |
String mapSchemaStr = mapper.writeValueAsString(jsonSchema); | |
System.out.println(mapSchemaStr); | |
} | |
// output | |
/* | |
{ | |
"type": "object", | |
"id": "urn:jsonschema:MyClass", | |
"properties": { | |
"reference": { | |
"type": "string", | |
"maxLength": 14, | |
"minLength": 14 | |
}, | |
"codeBank": { | |
"type": "string", | |
"pattern": "^\\d{5}$" | |
} | |
} | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment