Grant NEALE
Grant NEALE

Reputation: 13

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
   }
}

This works only of the Data is sent under a json Object

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

But I can't parse the object if it is sent like this with a key: poll!

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

This is the solution I used using the answer below:

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
        }
    }

Upvotes: 1

Views: 669

Answers (1)

0xTim
0xTim

Reputation: 5565

You need to tell Vapor how your request looks with a PollRequestData object which would look like:

struct PollRequestData: Content {
  let poll: Poll
}

Your decode then looks like: let poll = try req.content.decode(PollRequestData.self).poll

Upvotes: 1

Related Questions