我想描述一个具有数组类型属性的对象的模式。该数组中的项目必须属于同一类型。但是,对于该数组中的项,两个不同的对象可以具有不同的类型:
// object_1
{
<...>,
"array_of_some_type": [1, 2, 3, 4, 5],
<...>
}
// object_2
{
<...>,
"array_of_some_type": ["one", "two", "three"],
<...>
}
我尝试使用oneOf
关键字:
{
"type": "object",
"properties": {
<...>
"array_of_some_type": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"oneOf": [
{ "type": "number" },
{ "type": "string" },
{ "type": "object" }
]
},
"additionalItems": false
},
<...>
},
"required": [ "array_of_some_type" ],
"additionalProperties": false
}
但这是错误的,因为这个模式在我的case对象中对invalid是有效的:
// invalid_object
{
<...>,
"array_of_some_type": [1, "two", 3],
<...>
}
正确的架构可能如下所示:
{
"type": "object",
"properties": {
<...>
"array_of_some_type": {
"oneOf": [
{
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": { "type": "number" },
"additionalItems": false
},
{
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": { "type": "string" },
"additionalItems": false
},
{
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": { "type": "object" },
"additionalItems": false
}
]
},
<...>
},
"required": [ "array_of_some_type" ],
"additionalProperties": false
}
但是有很多相同数组属性的副本。 有没有办法调整第二个架构以避免重复?还是其他任何建议?
答案 0 :(得分:0)
您只能放置oneOf
子句中不同的部分。我认为JSON-Schema必须支持类似Java的泛型,才能表达清洁。
{
"type": "object",
"properties": {
"array_of_some_type": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"oneOf": [
{ "items": { "type": "number" } },
{ "items": { "type": "string" } },
{ "items": { "type": "object" } }
]
}
},
"required": [ "array_of_some_type" ],
"additionalProperties": false
}