【发布时间】:2018-07-09 16:39:32
【问题描述】:
我想知道如何为一组不同的对象指定 JSON 模式。 This thread 给了我一半的答案,但是当我对每种类型的对象都有多个实例时会失败。
这是一个示例 XML,基于 example given here 但重复了“Product”对象:-
{
"things": [
{
"entityType" : "Product",
"name" : "Pepsi Cola",
"brand" : "pepsi"
},
{
"entityType" : "Product",
"name" : "Coca Cola",
"brand" : "coke"
},
{
"entityType" : "Brand",
"name" : "Pepsi Cola"
}
]
}
只有当每种类型都有一个实例时(即“Product”只出现一次),以下架构才会验证上述 XML。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "https://schemas.example.com/things",
"title": "Things",
"description": "Some things",
"type": "object",
"required": [
"things"
],
"properties": {
"things": {
"type": "array",
"items": [
{
"type": "object",
"required": [
"entityType",
"name"
],
"properties": {
"entityType": {
"type": "string",
"enum": [
"Product"
]
},
"name": {
"type": "string"
},
"brand": {
"type": "string"
}
}
},
{
"type": "object",
"required": [
"entityType",
"name"
],
"properties": {
"entityType": {
"type": "string",
"enum": [
"Brand"
]
},
"name": {
"type": "string"
}
}
}
]
}
},
"additionalProperties": false
}
为了增加娱乐性,我不能使用像“AnyOf”这样的关键字,因为我将此架构嵌入到 Swagger 2.0 文档中,并且不支持这些关键字。
谢谢,
J.
【问题讨论】:
-
对象可以有其他不同的属性名称吗?在您的示例中,它们都具有几乎相同的结构,只是
brand属性是可选的。 -
不,它们完全不同;只有几个属性具有相同的名称。
-
嗯...为什么对这个问题投反对票?
标签: json swagger jsonschema swagger-2.0