【问题标题】:Is it possible to create Swift Codable for plain k-v json?是否可以为普通的 k-v json 创建 Swift Codable?
【发布时间】: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) 方法会有所帮助。
  • 我会简单地将其解码为字典。就是这样。

标签: ios json swift


【解决方案1】:

您可以简单地将其解码为字典。然后,如果您愿意,可以将您的字典映射到您的候选结构数组中:


struct Welcome: Codable {
    let candidates: [Candidate]
}

struct Candidate: Codable {
    let name, info: String
}

let js = """
{
    "peopleA": "nnll",
    "peopleB": "ihyt",
    "peopleC": "udr",
    "peopleD": "vhgd",
    "peopleE": "llll"
}
"""

do {
    let dictionary = try JSONDecoder().decode([String: String].self, from: Data(js.utf8))
    let welcome = Welcome(candidates: dictionary.map(Candidate.init))
    print(welcome)  
} catch {
    print(error)
}

这将打印:

欢迎(候选人:[候选人(姓名:“peopleA”,信息:“nnll”),候选人(姓名:“peopleC”,信息:“udr”),候选人(姓名:“peopleB”,信息:“ihyt "), Candidate(name: "peopleE", info: "llll"), Candidate(name: "peopleD", info: "vhgd")])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2011-03-06
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多