Json有效载荷
{
"id": "test1",
"quantity": {
"amount": 10
}
}
Json模式
{
"type": "object",
"$schema": "http://json-schema.org/draft-06/schema#",
"properties": {
"id": {
"type": "string"
},
"category": {
"type": "string"
},
"quantity": {
"type": "object",
"properties": {
"amount": {
"type": "integer"
}
},
"required": ["amount"]
}
},
"required": [
"id",
"quantity"
]
}
使用org.everit.json.schema库进行验证。
SchemaLoader schemaLoader = SchemaLoader.builder().schemaJson(jsonSchema).build();
Schema schema = schemaLoader.load(jsonSchema, SchemaClient.classPathAwareClient());
schema.validate(jsonSubject);
验证对于必填字段有效。 但是要求也是要验证可选字段。 当JSON有效负载中缺少未标记为“必需”的字段时,有什么方法可以显示警告。 例如在上述情况下,要求在JSON有效负载中缺少“类别”时显示警告。