简体   繁体   English

Swift 使用未知密钥解码 JSON

[英]Swift decode JSON with unknown keys

I have a JSON file in my app bundle that looks like this我的应用程序包中有一个 JSON 文件,看起来像这样

{
    "1": "cat",
    "2": "dog",
    "3": "elephant"
}

What I'd like is to be able to find the value for the "2" key for example ("dog").我想要的是能够找到例如“2”键的值(“狗”)。

I'm using this extension to decode the json file:我正在使用这个扩展来解码 json 文件:

let config = Bundle.main.decode(Config.self, from: "config.json")

And I have this struct defined:我定义了这个结构:

struct Config: Codable {
    let id: String
    let animal: String
}

But how do I find the animal name for the "2" key?但是如何找到“2”键的动物名称?

You seem to be trying to decode your JSON as if it were an array of your Config structs - that would look like this:您似乎正在尝试解码您的 JSON ,就好像它是您的Config结构的数组一样-看起来像这样:

[
  {
    "id": "1",
    "animal": "cat"
  },
  {
    "id": "2",
    "animal": "dog"
  },
  {
    "id": "3",
    "animal": "elephant"
  }
]

But your data (config.json) isn't that, it's just a JSON dictionary of String keys with String values.但是您的数据(config.json)不是那个,它只是一个带有字符串值的字符串键的 JSON 字典。

You can instead "decode" it as just a String: String dictionary like:您可以改为将其“解码”为 String: String 字典,例如:

let dict = Bundle.main.decode([String: String].self, from: "config.json")

and then dict["2"] would indeed be an optional string, with a value of .some("dog")然后dict["2"]确实是一个可选字符串,其值为.some("dog")

Or perhaps you mean your JSON to be an array of Config 's, if you change the contents of config.json file to the above, and then decode it with:或者,如果您将config.json Config的内容更改为上述内容,然后将其解码为:

let config = Bundle.main.decode([Config].self, from: "config.json")

Then the animal with id of 2 would be, eg那么 id 为 2 的动物将是,例如

config.first(where: { $0.id == "2" })?.animal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM