这是一个与 swift 上的 JSONDecoder 可编码功能相关的模型设计相关问题。
我有以下 JSON:
"author": {
"name": "abc",
"emailAddress": "abc@xyz.com",
"id": 8665,
"displayName": "A B C",
"active": true,
"slug": "abc",
"type": "NORMAL",
"links": {
"self": [
{
"href": "some_href"
}
]
}
}
我正在尝试使用新的 swift 4 Codeable 功能对此进行解码。
因此我创建了我的结构如下:
struct Author: Codeable {
let name: String,
let emailAddress: String,
let id: String,
let displayName: String,
let active: String,
let type: String,
let links: [String: [Link]]
}
struct Link: Codeable {
let href: String
}
一旦我在这个 json 上运行 JSONDecoder().decode,我就会得到上述格式的模型对象。但是,Author 类中的 links 属性是作为字典获取的。现在要访问 self 字段的值,我需要大致执行以下操作:
let selfLink = author.links["self"]
let href = selfLink[0].href
有没有更好的方法来为结构建模以避免这种情况?