json - JSON Swift.DecodingError.keyNotFound(Swift 5.3)
问题描述
我是 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
解决方案
您的内容是数组而不是字典,您需要[CurrentConditions].self
do {
let response = try JSONDecoder().decode([CurrentConditions].self, from: jsonData)
}
catch {
print(error)
}
始终避免try!
和使用do catch
块
推荐阅读
- extjs - 如何为远程组合框呈现初始值的显示字段?
- flutter - Flutter - 非 CamelCase 的 Objectbox 生成附加选项
- python - 如何使用带参数的任务计划程序运行 python 脚本
- firebase - Firebase.initializeApp() 给出错误:空值检查运算符用于空值
- c# - 如何随机激活 2 个游戏对象?
- javascript - Next.js:您可能需要适当的加载器来处理此文件类型,目前没有配置加载器来处理此文件
- r - ggarrange 始终用轴标题覆盖右下 x 轴
- maple - 在 Maple 中,当使用 plot3d 绘制参数和笛卡尔坐标表面的组合时,如何指定 x、y 和 t 的范围?
- compiler-errors - 为什么 NVCC 对 constexpr 比非 constexpr 主机函数更严格?
- java - 检查西班牙身份证信的Java程序