You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swagger中描述含简单对象的数组模型?

在Swagger YAML中描述元素结构不固定的数组

你要描述的是元素结构不固定的对象数组(每个数组元素的属性各不相同),在Swagger(OpenAPI)的YAML模型里可以按以下两种场景处理:

场景1:允许数组元素是任意结构的对象

如果不需要限制元素的具体属性,只要求是任意键值对的对象,直接定义数组类型,并指定items为带additionalProperties: true的对象即可:

components:
  schemas:
    ArbitraryObjectArray:
      type: array
      items:
        type: object
        additionalProperties: true

如果接口直接接收这个数组作为请求体,在接口定义里引用该模型:

paths:
  /your-target-endpoint:
    post:
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ArbitraryObjectArray'

场景2:精确限定元素的可选属性

如果需要严格匹配你给出的示例(每个元素只能包含name/class/hello其中一个必填属性),可以用oneOf来定义单个元素的结构,再组合成数组:

components:
  schemas:
    SinglePropertyObject:
      oneOf:
        - type: object
          required: [name]
          properties:
            name:
              type: string
        - type: object
          required: [class]
          properties:
            class:
              type: string
        - type: object
          required: [hello]
          properties:
            hello:
              type: string
    SpecificSinglePropertyArray:
      type: array
      items:
        $ref: '#/components/schemas/SinglePropertyObject'

这种写法会明确约束每个数组元素只能是包含指定单一属性的对象,完全匹配你提供的示例格式。

内容的提问来源于stack exchange,提问作者asim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:31:21