代码之家  ›  专栏  ›  技术社区  ›  Grant NEALE

如何解析正文中发送的json对象(请求)

  •  1
  • Grant NEALE  · 技术社区  · 7 年前
    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
            }
        }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   0xTim    7 年前

    你需要用 PollRequestData 对象,其外观如下:

    struct PollRequestData: Content {
      let poll: Poll
    }
    

    您的解码如下所示: let poll = try req.content.decode(PollRequestData.self).poll