【发布时间】:2018-10-30 13:51:50
【问题描述】:
我正在尝试在 codable 的帮助下解码 JSON - https://pastebin.com/Xfjj2XiP
但是,当我这样做时,我得到了这个错误。
typeMismatch(Swift.Dictionary
, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "txt_forecast", intValue: nil)], debugDescription: "预期解码 Dictionary 但找到了一个数组。”,基础错误:无))
这是我正在使用的代码:
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)
}
}
【问题讨论】: