Swagger UI数组示例显示异常,OpenAPI 3.0.0请求体配置求助
问题原因及解决方案
你的问题主要出在两个地方:OpenAPI 3.0规范中数组示例的写法错误,以及示例字段与Schema定义不匹配,导致Swagger UI无法正确解析示例结构,进而显示成了orderedmap而非正常的数组对象。
具体原因分析
数组Schema的
examples格式不符合规范
在OpenAPI 3.x中,Schema对象的examples字段需要是一个命名示例的键值对集合,每个示例要包含summary(可选)和value(必填)。你直接把数组元素放在examples下,属于格式错误,Swagger UI无法正确识别。如果是单个示例,应该使用example字段而非examples。示例字段与Schema定义不匹配
你的ItemSchema定义的属性是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定义,避免出现字段名不一致(比如你之前的
textvsname)的情况。 - 刷新Swagger UI后,就能看到正常显示的数组示例了,不再是orderedmap。
内容的提问来源于stack exchange,提问作者Gobliins
相关产品推荐
相关产品推荐

