如何在Swagger中定义包含多层嵌套数组的API响应OpenAPI规范
如何在Swagger中定义包含多层嵌套数组的API响应OpenAPI规范
我来帮你搞定这个多层嵌套结构的OpenAPI响应定义问题~先看你之前的尝试里有几个容易踩的小坑,比如legal_units其实是对象类型不是数组,还有部分引用的层级没对齐,导致SwaggerHub没法正确渲染结构。下面是修正后的完整规范,完全匹配你给出的示例响应:
components: schemas: ControlAttributes: type: object description: 顶层响应结构 properties: version: type: string description: 版本号 example: "1.0" calculatedDateTime: type: string description: 计算时间 example: "20230320 134724" brand: type: array description: 品牌数组 items: $ref: '#/components/schemas/Brand' legal_units: type: object description: 法定单位对象 $ref: '#/components/schemas/LegalUnits' Brand: type: object description: 品牌对象 properties: brandCode: type: string example: "RET" market: type: array description: 市场数组 items: $ref: '#/components/schemas/Market' Market: type: object description: 市场对象 properties: ValueCode1: type: string example: "ABC" ValueCode2: type: string example: "A192" product: type: array description: 产品数组 items: $ref: '#/components/schemas/Product' market_units: type: object description: 市场单位对象 $ref: '#/components/schemas/MarketUnits' Product: type: object description: 产品对象 properties: ProductFeat1: type: string example: "A9" ProductFeat2: type: string example: "100CD" ProductFeat3: type: string example: "3" ProductFeat4: type: string example: "20230313 000000" ProductFeat5: type: string example: "cert" MarketUnits: type: object description: 市场单位明细 properties: UnitCategory1: type: string example: "g/km" UnitCategory2: type: integer example: 0 UnitCategory3: type: string example: "l/100km" UnitCategory4: type: string example: "Wh/km" LegalUnits: type: object description: 法定单位明细 properties: LegalUnitCategory1: type: string example: "g/km" LegalUnitCategory2: type: string example: "l/100km" LegalUnitCategory3: type: string example: "Wh/km" LegalUnitCategory4: type: string example: "km" LegalUnitCategory5: type: string example: "kg" LegalUnitCategory6: type: string example: "N"
重点给你划几个关键调整点:
- 把你之前错误定义成数组的
legal_units改成了对象类型,完全匹配示例里的结构 - 给每个嵌套层级都明确了数组类型和对应的items引用,比如
brand数组的每个元素是Brand对象,Brand里的market又是数组,每个元素是Market对象,以此类推 - 统一了schema的命名格式(首字母大写),这样在SwaggerHub里更易读
- 补充了清晰的描述字段,方便后续维护
把这段代码放到SwaggerHub里,就能完美渲染出你想要的嵌套响应结构啦~
备注:内容来源于stack exchange,提问作者Aks
相关产品推荐
相关产品推荐

