簡體   English   中英

是否可以為普通的 kv json 創建 Swift Codable?

[英]Is it possible to create Swift Codable for plain k-v json?

我有 JSON 數據,如:

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

有成千上萬的這樣的數據,基本上我想做的是讀取 JSON 文件,並獲取相關信息,例如:輸入peopleC ,返回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 中工作?

您可以簡單地將其解碼為字典。 然后,如果您願意,可以將字典映射到候選結構數組中:


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”)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM