我的應用程式包中有一個 JSON 檔案,看起來像這樣
{
"1": "cat",
"2": "dog",
"3": "elephant"
}
我想要的是能夠找到例如“2”鍵的值(“狗”)。
我正在使用這個擴展來解碼 json 檔案:
let config = Bundle.main.decode(Config.self, from: "config.json")
我定義了這個結構:
struct Config: Codable {
let id: String
let animal: String
}
但是如何找到“2”鍵的動物名稱?
uj5u.com熱心網友回復:
您似乎正在嘗試解碼您的 JSON,就好像它是您的Config
結構陣列一樣 - 看起來像這樣:
[
{
"id": "1",
"animal": "cat"
},
{
"id": "2",
"animal": "dog"
},
{
"id": "3",
"animal": "elephant"
}
]
但是您的資料(config.json)不是那樣,它只是一個帶有字串值的字串鍵的 JSON 字典。
您可以改為將其“解碼”為 String: String 字典,例如:
let dict = Bundle.main.decode([String: String].self, from: "config.json")
然后dict["2"]
確實是一個可選字串,其值為.some("dog")
或者,如果您將config.json檔案的Config
內容更改為上述內容,然后將其解碼為:
let config = Bundle.main.decode([Config].self, from: "config.json")
那么 id 為 2 的動物將是,例如
config.first(where: { $0.id == "2" })?.animal
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/507550.html