如何解析 Body(Request) 中发送的 json 对象

How to parse a json object sent in Body(Request)

func createPoll(on req: Request) throws -> String {
   let poll = try req.content.decode(Poll.self)

   return poll.save(on: req).map(to: Poll.self) {
      return poll
   }
}

这仅适用于在 json 对象

下发送的数据
{
  "title": "Once Poll",
  "option1": "Black finish",
  "option2": "Dark Gray finish",
  "votes1": 10,
  "votes2": 0
}

但是如果对象像这样用密钥发送,我无法解析对象:poll!

{
  "poll": {
    "title": "Once Poll",
    "option1": "Black finish",
    "option2": "Dark Gray finish",
    "votes1": 10,
    "votes2": 0
  }
}

这是我使用以下答案的解决方案:

struct PollRequestObject: Content {
let poll: Poll?

}

 func createPoll(on req: Request) throws -> Future<Poll> {
        guard let poll = try req.content.decode(PollRequestObject.self).poll else {
            throw Abort(.badRequest)
        }

        return poll.save(on: req).map(to: Poll.self) {
            return poll
        }
    }

您需要使用 PollRequestData 对象告诉 Vapor 您的请求看起来像:

struct PollRequestData: Content {
  let poll: Poll
}

你的解码看起来像:let poll = try req.content.decode(PollRequestData.self).poll