I have read about every stackoverflow question on this I can find, but sadly none of the solutions worked for me.
The goal is to convert a JSON file with the following example structure:
[{"id":"1","poltopf_id":"22441208220850191","bearbeitungszeit":"13.35","station":"1"},{"id":"2","poltopf_id":"22441208220813267","bearbeitungszeit":"-2270785619.97","station":"1"}, {"id":"3","poltopf_id":"2244120822087035","bearbeitungszeit":"-2270785551.27","station":"1"}]
to the following struct:
struct ProcessingTimeRow: Decodable {
let elementNo: Int
let poltopf_id: Double
let processingTime: Double
let station: Int
enum CodingKeys : String, CodingKey {
case elementNo = "id"
case poltopf_id
case processingTime = "bearbeitungszeit"
case station
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
elementNo = try values.decode(Int.self, forKey: .elementNo)
poltopf_id = try values.decode(Double.self, forKey: .poltopf_id)
processingTime = try values.decode(Double.self, forKey: .processingTime)
station = try values.decode(Int.self, forKey: .station)
}
}
This is where data is downloaded and attempted to be decoded:
URLSession.shared.dataTask(with: urlToDownload) {
(data, response, error) in guard let data = data else {
print("Something
went wrong with data")
return
}
do {
self.dataReceived = true
let decoder = JSONDecoder()
let urlData = try decoder.decode([ProcessingTimeRow].self, from: data)
print("UrlData: \(dump(urlData))")
} catch let err {
// Failed at downloading data
self.dataReceived = false
print("Error", dump(err))
}
}.resume()
Sadly I am getting the following error:
Swift.DecodingError.typeMismatch
▿ typeMismatch: (2 elements)
- .0: Swift.Int #0
▿ .1: Swift.DecodingError.Context
▿ codingPath: 2 elements
▿ _JSONKey(stringValue: "Index 0", intValue: 0)
- stringValue: "Index 0"
▿ intValue: Optional(0)
- some: 0
- CodingKeys(stringValue: "id", intValue: nil)
- debugDescription: "Expected to decode Int but found a string/data instead."
- underlyingError: nil
I would be very grateful if anyone can point me in the right direction!
Thank you!