json - SWIFT:将 JSON 对象解码为结构
问题描述
我正在尝试将 json 数据解析为可解码的结构。我很困惑,因为我不知道如何在没有每个数组的键的情况下映射对象数组。我拥有的json是:
{
"table": [
{
"name": "Liverpool",
"win": 22,
"draw": 1,
"loss": 0,
"total": 67
},
{
"name": "Man City",
"win": 16,
"draw": 3,
"loss": 5,
"total": 51
}
]
}
这是我当前的结构:
struct Table: Decodable {
let name: String
let win: Int
let draw: Int
let loss: Int
let total: Int
}
我只是想做类似的事情:
let tables = try! JSONDecoder().decode([Table].self, from: jsonData)
我得到的错误是:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"name\", intValue: nil) (\"name\").", underlyingError: nil))
解决方案
您忽略了根对象,即带有键的字典table
struct Root: Decodable {
let tables : [Table]
enum CodingKeys : String, CodingKey { case tables = "table" }
}
struct Table: Decodable {
let name: String
let win: Int
let draw: Int
let loss: Int
let total: Int
}
do {
let result = try JSONDecoder().decode(Root.self, from: jsonData)
let tables = result.tables
} catch { print(error) }
推荐阅读
- ios - 更新照片后 Firebase Swift 崩溃
- html - 与动画一起使用时,背面可见性不起作用
- azure - 创建自签名证书并将其上传到 Azure 应用服务的最简单方法
- android - 从 Activity 返回时如何获取最后一个 ListView 状态
- java - 为什么我在运行 Spring Boot 项目时总是得到状态为“404”的 Whitelabel 错误页面
- emacs - 带有常春藤/律师的 Emacs (26.3) 挂在查找文件上
- python - 如何使用 Python 和 Tkinter 绘制熊猫数据框的各个元素
- python - 如果 3 个或更多值(天)缺少数据,则删除日期范围内的所有行
- java - Linux:Maven exec:java 找不到主类
- java - JButton 没有填满整个 JPanel