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

Swagger UI数组示例显示异常,OpenAPI 3.0.0请求体配置求助

问题原因及解决方案

你的问题主要出在两个地方:OpenAPI 3.0规范中数组示例的写法错误,以及示例字段与Schema定义不匹配,导致Swagger UI无法正确解析示例结构,进而显示成了orderedmap而非正常的数组对象。

具体原因分析

  1. 数组Schema的examples格式不符合规范
    在OpenAPI 3.x中,Schema对象的examples字段需要是一个命名示例的键值对集合,每个示例要包含summary(可选)和value(必填)。你直接把数组元素放在examples下,属于格式错误,Swagger UI无法正确识别。如果是单个示例,应该使用example字段而非examples。

  2. 示例字段与Schema定义不匹配
    你的Item Schema定义的属性是id和name,但示例里写的是id和text,字段名不匹配会导致UI解析异常,显示为无序映射(orderedmap)。

修正后的完整API定义

下面是两种正确的写法,你可以根据需求选择:

写法1:在Schema中定义示例(适合复用示例)

post:
  tags:
    - test
  summary: Test dummy
  operationId: requestBodyTests
  requestBody:
    description: test the body
    required: true
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/Items'
components:
  schemas:
    Items:
      type: array
      items:
        $ref: '#/components/schemas/Item'
      # 单个示例用example,直接放数组内容
      example:
        - id: bla
          name: blubb
        - id: foo
          name: bar
    Item:
      type: object
      properties:
        id:
          type: string
        name:
          type: string

写法2:在requestBody的content中定义示例(更推荐,关联请求体)

这种方式可以直接为当前请求体指定示例,Swagger UI会优先加载这里的示例,适合不同接口有不同示例的场景:

post:
  tags:
    - test
  summary: Test dummy
  operationId: requestBodyTests
  requestBody:
    description: test the body
    required: true
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/Items'
        # 这里定义请求体的示例,支持多个命名示例
        examples:
          sampleItemArray:
            summary: Two sample items
            value:
              - id: bla
                name: blubb
              - id: foo
                name: bar
          singleItemExample:
            summary: Single item in array
            value:
              - id: single-id
                name: single-item-name
components:
  schemas:
    Items:
      type: array
      items:
        $ref: '#/components/schemas/Item'
    Item:
      type: object
      properties:
        id:
          type: string
        name:
          type: string

额外注意事项

  • 如果需要定义多个示例,使用examples(键值对形式);单个示例用example(直接放值),不要混淆两者的用法。
  • 确保示例中的字段名、类型完全匹配Schema定义,避免出现字段名不一致(比如你之前的text vs name)的情况。
  • 刷新Swagger UI后,就能看到正常显示的数组示例了,不再是orderedmap。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:32:48