Swagger documentation explains how to define arrays that contain mixed types ,例如 ["foo", 5, -2, "bar"]
。但是,我如何定义一个数组必须包含 either 一种类型的项目(字符串,["foo", "bar"]
)或另一种类型的项目(整数,[5, -2]
)?
我已经试过了,但是 Swagger UI 无法渲染它,所以我猜这是错误的:
oneOf:
- items:
- $ref: '#/components/schemas/SchemaA'
- items:
- $ref: '#/components/schemas/SchemaB'
最佳答案
首先,请记住 oneOf
仅在 OpenAPI 3.0 (openapi: 3.0.0
) 中受支持,但在 OpenAPI 2.0 中不受支持 (swagger: '2.0 '
).
您的场景可以使用 oneOf
定义,如下所示:
oneOf:
- type: array
items:
type: string
- type: array
items:
type: integer
- type: array
items:
$ref: '#/components/schemas/SchemaA'
在 vanilla JSON Schema 中,type: array
可以移出 oneOf
并放在 oneOf
旁边,但我不确定 OpenAPI 是否允许这样做(OpenAPI 规范对此不明确)。
type: array
oneOf:
- items:
type: string
- items:
type: integer
- items:
$ref: '#/components/schemas/SchemaA'
I've tried this, but Swagger UI can't render it
目前,Swagger UI 不会自动为 oneOf
和 anyOf
模式生成示例(参见 this issue)。解决方法是在 oneOf
旁边手动添加一个 example
:
example: [1, 2, 3] # <------
oneOf:
- type: array
items:
type: string
- type: array
items:
type: integer
- type: array
items:
$ref: '#/components/schemas/SchemaA'
关于swagger - 如何使用 OpenAPI/Swagger 定义数组项的排除类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56681569/