【发布时间】:2021-02-10 10:28:29
【问题描述】:
我是 Swift 新手,我正在尝试解码 JSON,但它不起作用。
这是 JSON 代码:
[
{
"LocalObservationDateTime": "2021-02-09T21:11:00+01:00",
"EpochTime": 1612894260,
"WeatherText": "Sunny",
"WeatherIcon": 36,
"HasPrecipitation": false,
"IsDayTime": false,
"Temperature": {
"Metric": {
"Value": 15.2,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 59,
"Unit": "F",
"UnitType": 18
}
},
"MobileLink": "http://m.accuweather.com/",
"Link": "http://www.accuweather.com/"
}
]
这是我创建的结构:
struct CurrentConditions : Decodable{
let localObservationDateTime: String?
let epochTime: Int
let weatherText: String
let weatherIcon: Int
let hasPrecipitation: Bool
let isDayTime: Bool
let temperature: Temperature
}
struct Temperature : Decodable{
let metric: Metric
let imperial: Imperial
}
struct Imperial : Decodable{
let value: Int
let unit: String
let unitType: Int
}
struct Metric : Decodable{
let value: Double
let unit: String
let unitType: Int
}
let response = try! JSONDecoder().decode(CurrentConditions.self, from: jsonData)
我使用此代码进行解码,但所有变量都为零。
解码器可以解决结构,但它是零。当我将“CurrentConditions”放入数组中时(像这样:[CurrentConditions])解码器无法解决结构和对象(响应)为零。
Fatal error: 'try!' expression unexpectedly raised an error:
Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>,
Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode
Dictionary<String, Any> but found an array instead.", underlyingError: nil)): file
JSON_Test/ViewController.swift, line 52
2021-02-10 13:13:22.429097+0300 JSON Test[7884:534414] Fatal error: 'try!' expression
unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String,
Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode
Dictionary<String, Any> but found an array instead.", underlyingError: nil)): file
JSON_Test/ViewController.swift, line 52
【问题讨论】:
-
请查看 JSON。它以代表数组的
[开头。这正是错误消息所说的。解码[CurrentConditions].self