Análise codificável Swift keyNotFound

Sep 09 2020

Estou tendo problemas para fazer a codificação funcionar. Qualquer ajuda seria muito apreciada. Eu tenho o seguinte no meu playground

Meu arquivo JSON

{
"metadata": {
  "generated": {
    "timestamp": 1549331723,
    "date": "2019-02-04 20:55:23"
  }
},
"data": {
    "CA": {
    "country-id": 25000,
    "country-iso": "CA",
    "country-eng": "Canada",
    "country-fra": "Canada"
    }
  }
}

Usei o aplicativo quicktype para ajudar a gerar as seguintes estruturas

// MARK: - Welcome
struct Welcome: Codable {
    let metadata: Metadata?
    let data: DataClass?
}

// MARK: - DataClass
struct DataClass: Codable {
    let ca: CA

    enum CodingKeys: String, CodingKey {
        case ca = "CA"
    }
}

// MARK: - CA
struct CA: Codable {
    let countryID: Int
    let countryISO, countryEng, countryFra: String

    enum CodingKeys: String, CodingKey {
        case countryID = "country-id"
        case countryISO = "country-iso"
        case countryEng = "country-eng"
        case countryFra = "country-fra"
    }
}

// MARK: - Metadata
struct Metadata: Codable {
    let generated: Generated?
}

// MARK: - Generated
struct Generated: Codable {
    let timestamp: Int?
    let date: String?
}

Código Swift:

 do {
        guard let url = Bundle.main.url(forResource: "data", withExtension: "json") else { return 0 }

        let jsonData = try Data(contentsOf: url)
        let decoder = JSONDecoder()

        let data = try decoder.decode(CA.self, from: jsonData)
        print (data)
        print(data.countryID)
        print(data.countryISO)
    } catch { print("error" , error) }

Esta é a mensagem de erro que recebo.

jsonData 244 bytes
error keyNotFound(CodingKeys(stringValue: "country-id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"country-id\", intValue: nil) (\"country-id\").", underlyingError: nil))

O valor está lá, não sei qual é o problema. Se eu remover o country-id do json e do modelo, obtenho o mesmo erro para country-iso.

Respostas

1 DávidPásztor Sep 09 2020 at 13:56

Isso porque você está tentando decodificar o tipo errado. O CAtipo está aninhado em vários níveis em seu JSON, você precisa passar o tipo de raiz para JSONDecoder.decode.

let root = try decoder.decode(Welcome.self, from: jsonData)
guard let ca = root.data?.ca else { return 0 }
print(ca)