Swift Codable Parsing keyNotFound

Sep 09 2020

Sto riscontrando un problema nell'attivazione del codable. Qualsiasi aiuto sarebbe molto apprezzato. Ho quanto segue nel mio parco giochi

Il mio file 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"
    }
  }
}

Ho usato l'app quicktype per generare le seguenti strutture

// 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?
}

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

Questo è il messaggio di errore che ricevo.

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

Il valore c'è, non sono sicuro di quale sia il problema. Se prendo remove country-id dal json e dal modello, ottengo lo stesso errore per country-iso.

Risposte

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

Questo perché stai cercando di decodificare il tipo sbagliato. Il CAtipo è annidato su diversi livelli nel tuo JSON, devi passare il tipo root a JSONDecoder.decode.

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