【发布时间】:2018-06-03 12:00:28
【问题描述】:
{
"coord": {
"lon": -122.03,
"lat": 37.33
},
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 287.01,
"pressure": 1012,
"humidity": 77,
"temp_min": 282.15,
"temp_max": 290.15
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 290
},
"clouds": {
"all": 1
},
"dt": 1528023600,
"sys": {
"type": 1,
"id": 428,
"message": 0.0042,
"country": "US",
"sunrise": 1528030097,
"sunset": 1528082688
},
"id": 5341145,
"name": "Cupertino",
"cod": 200
}
我尝试使用以下代码将其解码为我的对象:
do {
let decoder = JSONDecoder()
let object = try decoder.decode(Object.self, from: data)
return object
} catch {
print("JSON Error: \(error)")
return Object(weather: Weather(), main: Main())
}
这是我的对象:
struct Object: Codable {
var weather: Weather
var main: Main
}
struct Weather: Codable {
var city = ""
var description = ""
var icon = ""
enum CodingKeys: String, CodingKey {
case city = "name"
case description = "main"
case icon
}
}
struct Main: Codable {
var temputure = ""
enum CodingKeys: String, CodingKey {
case temputure = "temp"
}
}
但我得到一个错误:
JSON 错误:typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "天气", intValue: nil)], debugDescription: "预计解码 字典,但找到了一个数组。”,基础错误: 无))
我想知道如何解决这个问题。
【问题讨论】:
-
嗯,错误的描述是这样的:
Expected to decode Dictionary but found an array instead。您的weather键不是对象,而是对象数组。 -
@MihaiFratu 我该如何解决这个问题?