尝试验证下面的JSON对JSON模式的多态类型对象数组
使用依赖关系
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.0.79</version>
<exclusions>
<exclusion>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</exclusion>
</exclusions>
</dependency>
有两种类型的车辆,“自行车”和“摩托车”和人可以有多个车辆
json缺少车辆类型“bicycle”的属性“petName”
{
"firstname" : "Jack",
"lastname" : "Sparrow",
"age" : "42",
"vehicles" : [
{
"type" : "bicycle",
"company" : "Hercules",
"isElectric" : false
},
{
"type" : "motorcycle",
"company" : "Hero",
"hp" : 340,
"isRich" : true
}
]
}
json-schema
{
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "object",
"required": [
"firstname",
"lastname",
"age",
"vehicles"
],
"properties": {
"firstname": {
"type": "string",
"minLength": 2,
"maxLength": 10
},
"lastname": {
"type": "string"
},
"age": {
"type": [
"integer",
"string"
]
},
"vehicles": {
"type": "array",
"items": {
"type": "object",
"required": [
"type"
],
"properties": {
"company": {
"type": "string",
"minLength": 2,
"maxLength": 10
},
"isElectric": {
"type": "boolean"
},
"hp": {
"type": [
"string",
"integer"
]
},
"isRich": {
"type": "boolean"
},
"type": {
"type": "string",
"enum": [
"bicycle",
"motorcycle"
]
}
},
"additionalProperties": false
},
"anyOf": [
{
"properties": {
"type": {
"const": "bicycle"
},
"vehicles": {
"items": {
"required": [
"company",
"isElectric",
"petName"
]
}
}
}
},
{
"properties": {
"type": {
"const": "motorcycle"
},
"vehicles": {
"items": {
"required": [
"company",
"hp",
"isRich"
]
}
}
}
}
]
},
"additionalProperties": false
}
}
因此,在车辆类型“bicycle”中找不到属性“petName”应该是错误的,因为它是为它设置的必需字段,但没有引发错误。json模式有效吗?或者我遗漏了什么东西或犯了什么错误?
1条答案
按热度按时间bvn4nwqk1#
您的模式中有一些问题。让我们一次看一个。
additionalProperties
应该上移一级,这样它就不在properties
内部了。anyOf
在错误的位置。您正在向项添加约束,因此将anyOf
放在项架构上。anyOf
中的属性模式没有意义,因为“type”和“vehicles”不在同一个模式中。由于anyOf
在项目模式中,因此其模式应该根据项目中的值编写。1.您已将“petName”作为自行车的必需属性包含在内,但该属性未为车辆架构定义,并且不允许使用其他属性。您需要为“petName”定义架构或将其从
required
中删除一旦您修复了这些问题,您的模式应该可以按预期工作。