Swagger 文档解释了如何定义包含混合类型的数组,例如 ["foo", 5, -2, "bar"]
。但是,我如何定义数组必须包含一种类型的项目(字符串,["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'
我已经试过了,但是 Swagger UI 无法呈现它
目前,Swagger UI 不会自动生成oneOf
和anyOf
架构的示例(请参阅此问题(。解决方法是手动在oneOf
旁边添加example
:
example: [1, 2, 3] # <------
oneOf:
- type: array
items:
type: string
- type: array
items:
type: integer
- type: array
items:
$ref: '#/components/schemas/SchemaA'