如何在Swagger中编写嵌套对象和数组Schema?解决未知类型错误
解决Swagger嵌套Schema“未知类型”错误
你的问题核心是Swagger遵循JSON Schema规范,类型字段必须使用小写,你代码里多处用了大写的String、Number,这直接导致Swagger无法识别类型,出现“未知类型”提示。
以下是修复后的完整Swagger代码:
@swagger components: schema: Buyer: type: object properties: id: type: string Buyer_name: type: string Buyer_Delivery_Address: type: object properties: address_line: type: string City: type: string Postal_Code: type: number Country: type: string Buyer_Phone: type: number Buyer_Cart: # 注意:如果购物车是多个商品集合,这里应该用array类型而非object # 下面是数组结构的写法示例,可根据你的Node.js模型调整 type: array items: type: object properties: Product_ID: type: number Product_Name: type: string Product_quantity: type: number Product_Price: type: number @swagger /buyer: get: summary: 从数据库获取数据 description: 展示数据库中的所有数据 responses: 200: description: 成功展示数据库中的所有数据 content: application/json: schema: type: array items: $ref: '#components/schema/Buyer'
额外注意事项:
- 核对
Buyer_Cart的类型:如果你的Node.js模型中购物车是商品数组,必须将type设为array,并通过items定义单个商品的结构,否则无法正确映射数组类型。 - 保持YAML缩进一致:Swagger对缩进敏感,确保层级缩进统一(建议用2或4个空格)。
内容的提问来源于stack exchange,提问作者Sankalp Sachapara
相关产品推荐
相关产品推荐

