Swagger 2.0如何正确定义指定结构的对象数组JSON响应
解决方案
问题点说明
- 原定义中
searchTypeResp将STATE、COUNTRY设为同一个对象的属性,导致生成的数组元素会同时包含两个字段,不符合「每个数组对象仅包含其中一个字段」的需求 codeTable中的CODE_ID类型被错误定义为string,和目标响应中的数字类型不匹配
正确Swagger 2.0定义
responses: '200': description: 成功返回码表数据 schema: type: array items: type: object additionalProperties: type: array items: $ref: '#/definitions/codeTable' definitions: codeTable: title: codeTable type: object properties: CODE_NM: type: string CODE_DSC: type: string CODE_ID: type: integer # 修正类型为数字匹配目标结构 required: - CODE_NM - CODE_ID
如果你的环境支持OpenAPI 3.0+,可以用oneOf做更严格的字段约束,避免返回其他未定义的键:
openapi: 3.0.0 # 其余上层配置省略 components: schemas: codeTable: title: codeTable type: object properties: CODE_NM: type: string CODE_DSC: type: string CODE_ID: type: integer required: - CODE_NM - CODE_ID StateResp: type: object properties: STATE: type: array items: $ref: '#/components/schemas/codeTable' required: [STATE] CountryResp: type: object properties: COUNTRY: type: array items: $ref: '#/components/schemas/codeTable' required: [COUNTRY] paths: /your-api-path: get: responses: '200': description: 成功返回码表数据 content: application/json: schema: type: array items: oneOf: - $ref: '#/components/schemas/StateResp' - $ref: '#/components/schemas/CountryResp'
效果验证
上述定义生成的响应结构会完全匹配你的目标结构:数组包含两个独立对象,第一个仅含STATE字段,第二个仅含COUNTRY字段,字段类型和示例也完全对齐。
内容的提问来源于stack exchange,提问作者user1165270
相关产品推荐
相关产品推荐

