解码来自 json 具有特定结构的数据时出现问题

Problem decoding data from json with a specific structure

我正在尝试解码此响应数据:

{
  "headers": {},
  "original": {
      "code": 201,
      "success": true,
      "message": "Message"
  },
  "exception": null
}

使用这个结构:

struct MarcaAguaResData: Codable {
    let original: Marca
}

struct Marca: Codable {
    let code: Int
    let success: Bool
    let message: String
}

我只关心原创。使用我正在实施的代码,使用 JSONDecoder,我得到这个错误:

failure(Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "code", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"code\", intValue: nil) (\"code\").", underlyingError: nil)))

首先让我说 您提供的 JSON 和您提供的 Codable 工作得很好

但是,当您收到此特定错误时:

failure(Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "code", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "code", intValue: nil) ("code").", underlyingError: nil)))

这只是意味着 你的服务器没有发送你一直期望的 JSON,所以基本上在这个错误中你的服务器向你发送了这种 JSON:

{
  "headers": {},
  "original": {
      "success": true,
      "message": "Message"
  },
  "exception": null
}

JSON 中完全没有“代码”。

如果在结构中将 code 标记为可选,则可以避免出现错误 并且仍然可以使代码正常工作:

struct Marca: Codable {
    let code: Int?
    let success: Bool
    let message: String
}