我希望在 OpenAPI 中表示以下 JSON 对象:
{
"name": "Bob",
"age": 4,
...
}
属性的数量和属性名称未完全预先确定,因此我希望使用additionalProperties。但是,我不太确定它将如何通过 OpenAPI/Swagger 2.0 表示。我试过这个:
Person:
type: object
additionalProperties:
type:
- int
- string
或 JSON 等效项:
{
"Person": {
"type": "object",
"additionalProperties": {
"type": ["int", "string"]
}
}
}
但这并不完全有效。有什么方法可以保留我想要表示的 JSON 对象的结构,特别是字符串和整数,而不是任意对象类型?
最佳答案
OpenAPI 3.1
在 OpenAPI 3.1 中,type
关键字可以采用类型列表:
Person:
type: object
additionalProperties:
type: [string, integer]
OpenAPI 3.x
OpenAPI 3.0+ 支持 oneOf
,因此您可以使用:
Person:
type: object
additionalProperties:
oneOf:
- type: string
- type: integer
OpenAPI 2.0
OpenAPI 2.0 不支持多类型值。您最多可以使用 typeless schema ,这意味着附加属性可以是任何内容 - 字符串、数字、 bool 值等 - 但您无法指定确切的类型。
Person:
type: object
additionalProperties: {}
这相当于:
Person:
type: object
关于swagger - 通过Swagger/OpenAPI为additionalProperties指定多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46472543/