Search code examples
iosswiftjsondecoder

Problem decoding data from json with a specific structure


I'm trying to decode this response data:

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

With this struct:

struct MarcaAguaResData: Codable {
    let original: Marca
}

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

I only care about what is in original. With the code that I'm implementing, using a JSONDecoder, I get this error:

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

Solution

  • Let me start by saying that the JSON you provided and the Codable you provided works just fine.

    But, as you are getting this specific error:

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

    it just means that your server is not sending the JSON you are always expecting, so essentially in this error your server is sending you this kind of JSON:

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

    where the "code" is totally missing in the JSON.

    You could avoid getting the error and still getting your code to work if you mark code as optional in your struct:

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