如何在 OpenAPI 2.0 中定义混合类型数组(具有不同的元素类型)? [英] How to define a mixed-type array (with different element types) in OpenAPI 2.0?

查看:80
本文介绍了如何在 OpenAPI 2.0 中定义混合类型数组(具有不同的元素类型)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将以下 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.

OpenAPI 3.0 支持混合类型,使用 oneOf/anyOf 和可选的 nullable: true 也允许空值.

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 中定义混合类型数组(具有不同的元素类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆