如何在Swagger的response区段编写指定JSON结构文档并解决缩进报错
错误原因
- YAML缩进不规范:YAML语法对缩进要求严格,同层级属性必须左对齐,子层级属性要比父层级多缩进2个空格,你原有配置中
name、chat、messages等属性的缩进层级混乱,是触发bad indentation of a mapping entry报错的直接原因。 - 响应结构不匹配:你需要返回的JSON根节点是对象,包含
data(对象数组)、total、action三个属性,原有配置错误地将数组项和totalCount、action放在同一层级,还错误将total字段命名为totalCount、cat属性值写错,会导致示例和实际返回结构不一致。
正确配置
以下是符合OpenAPI 3.x规范的完整写法,既包含字段类型定义,也匹配你给出的JSON返回结构:
responses: '200': description: test data content: application/json: schema: type: object required: - data - total - action properties: data: type: array description: 业务数据列表 items: type: object properties: id: type: string nullable: true description: 数据ID name: type: string description: 用户名 chat: type: string description: 聊天ID messages: type: object description: 消息信息 properties: current: type: number nullable: true description: 当前页码 count: type: number nullable: true description: 消息总数 length: type: number nullable: true description: 消息长度 rows: type: array nullable: true description: 消息列表 type: type: string nullable: true description: 消息类型 cid: type: string description: 分类ID cat: type: string description: 分类标识 mark: type: boolean description: 是否标记 total: type: integer description: 数据总条数 action: type: string description: 接口请求状态 example: data: - id: "" name: "James" chat: "1" messages: current: null count: null length: null rows: null type: null cid: "204" cat: "messages" mark: false total: 200 action: "success"
如果你不需要定义字段类型和描述,只需要快速配置返回示例,也可以简化为以下写法:
responses: '200': description: test data content: application/json: schema: example: data: - id: "" name: "James" chat: "1" messages: current: null count: null length: null rows: null type: null cid: "204" cat: "messages" mark: false total: 200 action: "success"
内容的提问来源于stack exchange,提问作者user7282
相关产品推荐
相关产品推荐

