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
}
}
答案 0 :(得分:1)
您需要告诉Vapor您的请求与PollRequestData
对象的外观如下:
struct PollRequestData: Content {
let poll: Poll
}
您的解码如下:let poll = try req.content.decode(PollRequestData.self).poll