首页 > 解决方案 > 是否可以为普通的 kv json 创建 Swift Codable?

问题描述

我有 JSON 数据,例如:

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

有成千上万这样的数据,基本上我想做的是读取 JSON 文件,并获取相关信息,例如: input peopleC, return udr

尝试使用一些在线解决方案,我得到了

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 中工作?

标签: iosjsonswift

解决方案


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


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”),候选人(姓名:“peopleE”,信息:“llll”),候选人(姓名:“peopleD”,信息:“vhgd”)])


推荐阅读