Swift Vapor 对象数组解码错误

Swift Vapor wrong decoding of array of objects

我正在尝试将对象数组传递给另一个对象

struct CreationData: Encodable {
  enum CodingKeys: String, CodingKey {
    case property1
    case amount
    case participants
    case code
  }

  var property1: String?
  var amount: Double?
  var tipAmount: Double?
  var participants: [Participant]
  var currency: Currency

  init() {
    name = nil
    property1 = nil
    participants = []
    tipAmount = nil
    currency = .hryvna
  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    if let name = name {
      try container.encode(name, forKey: .name)
    }
    if let property1 = property1 {
      try container.encode(property1, forKey: .property1)
    }
    if let tipAmount = tipAmount {
      try container.encode(tipAmount, forKey: .tipAmount)
    }
    if !participants.isEmpty {
      try container.encode(participants, forKey: .participants)
    }
    try container.encode(currency, forKey: .currencyCode)
  }
}

数组中的对象在哪里

struct Participant: Hashable, Encodable {
  enum CodingKeys: String, CodingKey {
    case amount
    case id
  }

  var image: Data?
  var displayName: String
  var amount: Double? = 100
  var id: Int?

  var name: String?

  var isSelected: Bool = false

  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(amount, forKey: .amount)
    try container.encode(id, forKey: .id)
  }

}

所以我的 JSON 看起来像这样

{
  "property1" : 123,
  "code" : "zen",
  "name" : "No name",
  "participants" : [
    {
      "amount" : 100,
      "id" : 1
    }
  ]
}

在后端我使用这个处理程序

func createHandler(_ req: Request, splitCreate: Create) throws -> Future<SplitResponse> {
    let logger = try req.make(Logger.self)
    let user = try req.requireAuthenticated(User.self)
    guard let id = user.id else {
      throw Abort(.badRequest, reason: "Couldn't get an id for current user")
    }

    ...

使用此请求内容对象

struct Create: Content {
    struct Participant: Content {
      var id: Int?
      var amount: Double?
    }

    var amount: Double?
    var tipAmount: Double?
    var name: String?
    var participants: [Participant]
    var currencyCode: String
  }

我通过参与者数组创建枢轴,问题是不是像这样从数组中获取单个参与者

[App.Create.Participant(id: Optional(1), amount: Optional(100.0))]

在指定的后端 JSON 我得到这些参与者

[App.Create.Participant(id: Optional(1), amount: nil), App.Create.Participant(id: Optional(1), amount: Optional(100.0))]

似乎我的数组 json 解码不正确,但我无法找到修复它的方法

出于某种原因,将 Content-Type header 添加到 URLSessionConfiguration.additionalHeaders 并没有将编码更改为 JSON。 所以我不得不明确地将 Alamofire 的请求编码设置为 JSONEncoding.default