我有两个单独的JSON模式(用于验证REST API的HTTP请求端点),它们都接受相同的确切对象,但具有不同的必需字段(这是创建与更新请求).有没有办法可以重用此对象的单个定义并仅更改必填字段?我知道如何使用$ref重用对象作为另一个对象的属性,但我无法弄清楚如何将整个对象重用为模式中的顶级对象.到目前为止我失败的尝试:
event.json
{
"id": "event",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"start_date": {
"type": "integer"
},
"end_date": {
"type": "integer"
},
"description": {
"type": "string"
}
},
"additionalProperties": false
}
Run Code Online (Sandbox Code Playgroud)
事件create.json
{
"id": "event-create",
"type": "object",
"$ref": "event",
"additionalProperties": false,
"required": [ "name", "description" ]
}
Run Code Online (Sandbox Code Playgroud)
显然这不起作用.似乎它试图将"事件"的全部内容插入到"event-create"的定义中,包括ID等.我试过推荐event#/properties无济于事.我似乎无法$ref在属性属性中作为唯一值.有任何想法吗?
应忽略JSON Reference对象中除"$ ref"以外的任何成员.
- http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3
这就是为什么你的例子不起作用的原因.$ref应该忽略除了该字段之外的任何内容.
支持$ref仅限于类型为JSON Schema的字段.这就是为什么尝试使用它properties不起作用. properties是一个普通对象,其值为JSON模式.
最好的方法是使用allOf.在这种情况下,allOf可以将其视为mixin模式列表.
{
"id": "event-create",
"type": "object",
"allOf": [{ "$ref": "event" }],
"required": ["name", "description"]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2272 次 |
| 最近记录: |