如here 所述,jackson 验证器的功能开发已停止。
但是,到目前为止,我发现networknt 的 json 模式验证器非常活跃和有趣。您可以refer这些内容快速入门。
Maven 依赖
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.0.49</version>
</dependency>
代码片段 -
String jsonOrder = SampleUtil.getSampleJsonOrder();//replace or write
System.out.println(jsonOrder);
//Read json schema from classpaht
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7);
InputStream is = Thread.currentThread().getContextClassLoader()
.getResourceAsStream("order-schema.json");
JsonSchema schema = factory.getSchema(is);
//Read json to validate
try {
JsonNode node = mapper.readTree(jsonOrder);
Set<ValidationMessage> errors = schema.validate(node);
System.out.println("Errors in first json object: " + errors);
} catch (IOException e) {
e.printStackTrace();
}
//Test for invalid json
String emptyFoIdOrder = "{\"gtins\":[\"1\",\"2\",\"3\",\"4\"],\"storeId\":121,\"deliveryAddress\":\"Any street, some house - PIN 2021\"}/";
try {
JsonNode node = mapper.readTree(emptyFoIdOrder);
Set<ValidationMessage> errors = schema.validate(node);
System.out.println("Errors in first json object: " + errors);
} catch (IOException e) {
e.printStackTrace();
}
使用的示例 Json 方案-
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"title": "The root schema",
"description": "The root schema comprises the entire JSON document.",
"default": {},
"examples": [
{
"foId": "9876",
"gtins": [
"1",
"2",
"3",
"4"
],
"storeId": 121,
"deliveryAddress": "Any streeam, some house - PIN 2021"
}
],
"required": [
"foId",
"gtins",
"storeId",
"deliveryAddress"
],
"properties": {
"foId": {
"$id": "#/properties/foId",
"type": "string",
"title": "The foId schema",
"description": "An explanation about the purpose of this instance.",
"default": "",
"examples": [
"9876"
]
},
"gtins": {
"$id": "#/properties/gtins",
"type": "array",
"title": "The gtins schema",
"description": "An explanation about the purpose of this instance.",
"default": [],
"examples": [
[
"1",
"2"
]
],
"additionalItems": true,
"items": {
"$id": "#/properties/gtins/items",
"anyOf": [
{
"$id": "#/properties/gtins/items/anyOf/0",
"type": "string",
"title": "The first anyOf schema",
"description": "An explanation about the purpose of this instance.",
"default": "",
"examples": [
"1",
"2"
]
}
]
}
},
"storeId": {
"$id": "#/properties/storeId",
"type": "integer",
"title": "The storeId schema",
"description": "An explanation about the purpose of this instance.",
"default": 0,
"examples": [
121
]
},
"deliveryAddress": {
"$id": "#/properties/deliveryAddress",
"type": "string",
"title": "The deliveryAddress schema",
"description": "An explanation about the purpose of this instance.",
"default": "",
"examples": [
"Any streeam, some house - PIN 2021"
]
}
},
"additionalProperties": true
}