【发布时间】:2021-12-26 08:22:36
【问题描述】:
我有 JSON 数据,例如:
{
"peopleA": "nnll",
"peopleB": "ihyt",
"peopleC": "udr",
"peopleD": "vhgd",
"peopleE": "llll"
}
这样的数据成千上万,基本上我想做的是读取JSON文件,并获取相关信息,例如:输入peopleC,返回udr。
尝试使用一些online solution,我得到了
struct Welcome: Codable {
let peopleA, peopleB, peopleC, peopleD: String
let peopleE: String
}
我知道我可以将 JSON 文件重构为:
{
"candidates": [
{
"name": "peopleA",
"info": "nnll"
},
{
"name": "peopleB",
"info": "ihyt"
},
{
"name": "peopleC",
"info": "udr"
}
]
}
并获取相关的 Swift 结构体:
struct Welcome: Codable {
let candidates: [Candidate]
}
// MARK: - Candidate
struct Candidate: Codable {
let name, info: String
}
我只是想知道我们是否可以在不对 json 文件进行后处理的情况下使其在 Swift 中工作?
【问题讨论】:
-
也许覆盖
init(from decoder: Decoder)方法会有所帮助。 -
我会简单地将其解码为字典。就是这样。