问题描述
我试图将以下 JSON 映射到 OpenAPI 2.0 (Swagger 2.0) YAML 定义,但我不确定如何将混合数组类型设置到我的架构中:
I trying to map the following JSON to an OpenAPI 2.0 (Swagger 2.0) YAML definition, and I am not sure how to set mixed array types into my schema:
{
"obj1": [
"string data",
1
]
}
现在,我的 OpenAPI 定义有:
Now, my OpenAPI definition has:
schema:
object1:
type: array
items:
type: string
但这不允许在数组中使用整数.
but this doesn't allow integers inside the array.
有没有办法定义混合类型数组?
Is there a way to define a mixed type array?
推荐答案
答案取决于您使用的 OpenAPI 规范版本.
The answer depends on which version of the OpenAPI Specification you use.
type
可以是类型列表,因此您可以将架构编写为:
type
can be a list of types, so you can write your schema as:
# openapi: 3.1.0
obj1:
type: array
items:
type: [string, integer]
# or if nulls are allowed:
# type: [string, integer, 'null']
OpenAPI 3.0.x
OpenAPI 3.0 支持混合类型,使用 oneOf
/anyOf
和可选的 nullable: true
也允许空值.
OpenAPI 3.0.x
Mixed types are supported in OpenAPI 3.0 using oneOf
/ anyOf
and optionally nullable: true
to also allow nulls.
# openapi: 3.0.1
obj1:
type: array
items:
oneOf:
- type: string
nullable: true # If nulls are allowed
- type: integer
OpenAPI 2.0
OpenAPI 2.0 (Swagger 2.0) 并不真正支持混合类型的数组和参数.您最多可以为 items无类型架构
{}
/code>,这意味着项目可以是任何东西(除了 null
)——数字、对象、字符串等.你不能为 items
指定确切的类型,但你可以添加具有不同项目类型的数组的 example
.
OpenAPI 2.0
OpenAPI 2.0 (Swagger 2.0) does not really support mixed-type array and parameters. The most you can do is to use a typeless schema {}
for items
, which means the items can be anything (except null
) – numbers, objects, strings, etc. You cannot specify the exact types for items
, but you can add an example
of an array with different item types.
# swagger: '2.0'
obj1:
type: array
items: {} # <--- means "any type" (except null)
example:
- string data
- 1
注意: 无类型架构 {}
只能用于正文参数和响应架构.路径、标题和表单参数需要数组项的原始 type
.
Note: Typeless schema {}
can only be used in body parameters and response schemas. Path, header and form parameters require a primitive type
for array items.
这篇关于如何在 OpenAPI 2.0 中定义混合类型数组(具有不同元素类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!