【问题标题】:Swagger array of objects大摇大摆的对象数组
【发布时间】:2017-04-30 21:54:06
【问题描述】:

我在使用 swagger 时遇到了一些问题:我在 .yaml 文件中有一个以这种方式描述的对象(地址)数组:

Address:
  properties:
    street:
      type: string
    city:
      type: string
    state:
      type: string
    country:
      type: string

这是另一个带有 API 定义的 yaml 文件(地址是一个参数):

 - name: addresses
   in: formData
   description: List of adresses of the user. The first one is the default one.
   type: array
   items:
     $ref: '#/definitions/Address'

这是我在 swagger UI 中输入的文字:

[
  {
    "street": "Bond street",
    "city": "Torino",
    "state": "Italy",
    "country": "Italy"
  }
]

但在 node.js 中,如果我打印收到的内容:

{"地址":["["," {"," \"street\": \"邦德街\","," \"city\": \"Torino\","," \"state\": \"Italy\","," \"country\": \"意大利\""," }","]"]}

我得到一个解析错误...有一些额外的 [ 和 "。似乎招摇将它解析为字符串 (?)

【问题讨论】:

  • 你使用the .yaml file(带点)和the other yaml file(不带点)有什么意义吗?
  • 请发布您的完整 .yaml 文件。它们在同一个文件夹中吗?您使用什么代码在 Node.js 端打印数据?
  • 不,yaml 文件不在同一个文件夹中,但我认为这不是问题,因为 swagger ui 中的描述有效。要打印数据,我使用 JSON.stringify

标签: arrays object swagger


【解决方案1】:

要发送 JSON 数据,您需要使用 in: body 参数(不是 in: formData)并指定操作消耗 application/jsonformData 参数用于消耗application/x-www-form-urlencodedmultipart/form-data 的操作。

paths:
  /something:
     post:
       consumes:
         - application/json
       parameters:
         - in: body
           name: addresses
           required: true
           schema:
             type: array
             items:
               $ref: "#/definitions/Address"  # if "Address" is in the same file
               # or
               # $ref: "anotherfile.yaml#/definitions/Address"  # if "Address" is in another file

【讨论】:

  • 感谢您的所有建议。但无论如何,有些东西是行不通的。我更改了in:body,但仍然
  • 定义“不工作”。 Swagger UI 是否会错误地呈现这个?你后端收到不正确的数据吗?越详细越好。
  • 是的,抱歉昨天的简短回答。在我的 BE 中仍然收到错误的数据。
  • 您好,最后我能够修复它。我没有注意到架构的变化。谢谢。
猜你喜欢
  • 2018-08-17
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 2014-07-19
  • 2015-12-14
  • 2021-07-09
  • 1970-01-01
相关资源
最近更新 更多