Swagger配置formData接收对象数组报错,求正确配置方案
Swagger配置:FormData接收对象数组的报错解决
问题场景
你的Swagger配置代码如下:
/api/create: post: summary: --- description: ---- parameters: - in: formData name: products description: 'Array of key value pairs' required: true type: array items: type: object properties: id: type: string
配置报错提示Cannot have an array type in formData,需要让POST接口接收[{id:"sdsd"},{id:"dd"}]格式的对象数组作为formData输入。
解决方案
方案1:改用JSON请求体(推荐)
Swagger 2.0规范中,formData参数不支持嵌套的对象数组结构。最规范的做法是切换为application/json请求体传递复杂数据,修改配置如下:
/api/create: post: summary: --- description: ---- consumes: - application/json parameters: - in: body name: products description: 'Array of key value pairs' required: true schema: type: array items: type: object properties: id: type: string
前端只需以JSON格式发送请求体即可,这也是REST接口传递复杂数据的标准方式。
方案2:兼容formData的数组编码(仅适用于简单场景)
如果必须使用formData,需遵循formData的数组编码规则,将数组拆分为多个带索引的参数:
/api/create: post: summary: --- description: ---- parameters: - in: formData name: products[0].id description: 'Product ID at index 0' type: string required: true - in: formData name: products[1].id description: 'Product ID at index 1' type: string required: true # 可根据需求添加更多索引项,或设置为非必填支持动态数量
前端提交时需按照products[0].id=sdsd&products[1].id=dd的格式组装formData,但这种方式扩展性差,不适合动态长度的数组。
内容的提问来源于stack exchange,提问作者Rajan Lagah
相关产品推荐
相关产品推荐

