JSON Schema định nghĩa cấu trúc, validation, documentation cho JSON data. Jackson module jackson-module-jsonSchema generate schema từ Java class.
Dependency
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>2.15.2</version> <!-- match Jackson version -->
</dependency>
Ví dụ generate Schema từ POJO
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.*;
public class JsonSchemaTest {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
JsonSchema schema = schemaGen.generateSchema(Person.class);
String schemaJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
System.out.println(schemaJson);
}
}
class Person {
private String name;
private int age;
private List<String> courses;
private Address address;
// getters...
}
class Address {
private String firstLine, secondLine, thirdLine;
// getters...
}
Output (JSON Schema Draft v4)
{
"type" : "object",
"id" : "urn:jsonschema:Person",
"properties" : {
"name" : { "type" : "string" },
"age" : { "type" : "integer" },
"address" : {
"type" : "object",
"id" : "urn:jsonschema:Address",
"properties" : {
"firstLine" : { "type" : "string" },
"secondLine" : { "type" : "string" },
"thirdLine" : { "type" : "string" }
}
},
"course" : {
"type" : "array",
"items" : { "type" : "string" }
}
}
}
Ứng dụng JSON Schema
- Validation: Validate JSON input trước khi deserialize (dùng library
networknt/json-schema-validatorhoặceverit-org/json-schema). - Documentation: Tự động generate API docs (OpenAPI/Swagger dùng JSON Schema).
- Code generation: Generate POJO từ schema (jsonschema2pojo).
- Contract testing: Consumer-driven contract (Pact).
Validation Example (Networknt)
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
JsonSchema schema = factory.getSchema(schemaJsonString);
Set<ValidationMessage> errors = schema.validate(jsonNode);
if (!errors.isEmpty()) { /* handle validation errors */ }
Lưu ý
- Jackson module generate **Draft v4** (cũ). JSON Schema hiện tại là **Draft 2020-12**.
- Annotation Jackson ảnh hưởng schema:
@JsonProperty,@JsonIgnore,@NotNull(Bean Validation),@Size,@Pattern. - Polymorphic type: dùng
@JsonTypeInfođể generateoneOf/anyOf.