I am trying to decode a JSON with the help of codable - https://pastebin.com/Xfjj2XiP
However I'm getting this error when I do so.
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "txt_forecast", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
Here's the code I'm using:
struct container: Decodable {
var days: [forecastDay]
//Coding keys
enum CodingKeys: String, CodingKey {
case forecast = "forecast"
case txt_forecast = "txt_forecast"
case forecastday = "forecastday"
}
// Decoding
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let forecast = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .forecast)
let txt_forecast = try forecast.nestedContainer(keyedBy: CodingKeys.self, forKey: .txt_forecast)
let forecastdays = try txt_forecast.nestedContainer(keyedBy: CodingKeys.self, forKey: .forecastday)
let forecastdaysData = try forecastdays.decode(String.self, forKey: .forecastday)
days = try JSONDecoder().decode([forecastDay].self, from: forecastdaysData.data(using: .utf8)!)
print(days)
}
}
struct forecastDay: Decodable {
var period: Int?
var icon: String?
var title: String?
var fcttext: String?
//Coding keys
enum CodingKeys: String, CodingKey {
case period = "period"
case icon = "icon"
case title = "title"
case fcttext = "fcttext"
}
// Decoding
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
period = try container.decode(Int.self, forKey: .period)
icon = try container.decode(String.self, forKey: .icon)
title = try container.decode(String.self, forKey: .title)
fcttext = try container.decode(String.self, forKey: .fcttext)
}
}