簡體   English   中英

Swift 使用未知密鑰解碼 JSON

[英]Swift decode JSON with unknown keys

我的應用程序包中有一個 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”鍵的動物名稱?

您似乎正在嘗試解碼您的 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

暫無
暫無

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

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