json - jsonschema 验证使用 allof 和 complex if else
问题描述
在此处输入图像描述我有一个如下所示的 json 模式,我想根据 B 和 C 的值将定义加载到 D 和 E 中,因为我已经编写了 allOf 条件。我在应用程序中使用json-schema-validator进行 json 模式验证。
i)下面的模式总是作为有效的传递,因为 allOf 条件从未评估过,并且它没有从定义中加载像 maxLenth,multipleOf 这样的验证器属性。
ii)我怀疑我在错误的位置(根模式或子模式)进行了调节,我尝试将所有逻辑移动到子模式级别(在 B、C 和 D、E 内)
iii)我已经尝试执行https://json-schema.org/understanding-json-schema/reference/conditionals.html上提到的allOf示例,它也作为有效传递。为此,我确实在在线 josn 模式验证器http://json-schema-validator.herokuapp.com/上进行了验证,它也使用相同的库 json-schema-validator。
iv) JsonSchemaFactory 是否需要任何 ValidationConfiguration 来验证 Draft7 jsonSchema 条件,因为 Defaultlibrary 在此json-schema-validator上是 DRAFT-4 。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": [
"A",
"B",
"C",
"D",
"E"
],
"properties": {
"A": {
"type": "string"
},
"B": {
"type": "string",
"enum": ["TEST1","TEST2"]
},
"C": {
"type": "string",
"enum": ["TEST3","TEST4"]
},
"D": {
"type": "object"
},
"E": {
"type": "object"
}
},
"allOf": [
{
"if": {
"properties": { "B": { "const": "TEST1" } }
},
"then": {
"properties": { "D": { "$ref": "#/definitions/test" } }
}
},
{
"if": {
"properties": { "B": { "const": "TEST2" } }
},
"then": {
"properties": { "D": { "$ref": "#/definitions/testTwo" } }
}
},
{
"if": {
"properties": { "C": { "const": "TEST3" } }
},
"then": {
"properties": { "E": { "$ref": "#/definitions/testThree" } }
}
},
{
"if": {
"properties": { "C": { "const": "TEST4" } }
},
"then": {
"properties": { "E": { "$ref": "#/definitions/test4" } }
}
}
],
"definitions": {
"testOne":{"type":"object"},
"testTwo":{"type":"object"},
"testThree":{"type":"object"},
"testFour":{"type":"object"}
}
}
javaCode看起来像
@PostMapping("/sendMessage")
public ProcessingReport sendMessage(@RequestBody SampleRequest request) throws IOException, ProcessingException {
//step-1 writing request object into String
String requestJson = objectMapper.writeValueAsString(request);
//Step-2 getting jsonNode for requested json
JsonNode dataNode = JsonLoader.fromString(requestJson);
//step -3 creating jsonSchema factory(default)
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
//validating requested jsonNode(dataNode) against SchemaNode(schema of request json,which is loaded from resources)
ProcessingReport report = factory.getJsonSchema(schemaNode).validate(dataNode);
//Processing report resulting the given json validation is successful or not
if(!report.isSuccess()) {
System.out.println(report);
}
return report;
}
解决方案
推荐阅读
- wordpress - get_the_post_thumbnail 在添加类时添加垃圾
- macos - SwiftUI:如何在 MacOS 中用另一个视图替换视图
- java - 如何从 Java 中读取 proto3 自定义选项
- java - 宾果游戏 Java
- android - Xamarin 应用无法识别任何蓝牙设备 (Plugin.BluetoothLE)
- node.js - 在没有密码提示的情况下运行 sudo 命令
- java - 移动 3 个对象但保持对齐的公共方法
- android - 屏幕关闭时如何保持相机预览打开?
- java - 配置应用程序以 log4j2 故障登录 ActiveMQ
- sql - 检查 varchar 列是否只有字母字符