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

Swagger UI自引用字段示例值显示为string的问题咨询

解决Swagger递归对象示例显示错误的问题

当Swagger UI对递归引用的对象生成示例时,默认会用"string"作为占位符,这与实际的递归结构不符,可通过以下方法解决:

方法1:手动指定递归示例

在Schema定义中直接添加example字段,强制生成符合预期的递归结构。示例如下:

components:
  schemas:
    RecursiveObject:
      type: object
      properties:
        nextA:
          $ref: '#/components/schemas/RecursiveObject'
      # 手动定义递归示例,明确展示层级结构
      example:
        nextA:
          nextA: {}

这样Swagger UI会直接使用你指定的示例,而非默认的占位符。

方法2:结合nullable标记终止条件

如果递归允许在某一层级终止(比如nextA为null),可以明确标记nullable: true,并在示例中体现终止逻辑:

components:
  schemas:
    RecursiveObject:
      type: object
      properties:
        nextA:
          $ref: '#/components/schemas/RecursiveObject'
          nullable: true
      example:
        nextA:
          nextA: null

这种方式既符合递归规则,又清晰展示了递归的终止条件,避免误导。

补充说明

Swagger UI默认用"string"作为递归属性的示例,是为了避免无限递归生成示例导致的性能问题,但这会与实际结构冲突。手动指定example是最可靠的解决方案,能确保示例与Schema定义完全匹配。

内容的提问来源于stack exchange,提问作者Heiko Theißen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:32:04