如何使用 Codable 解码字典的 JSON 字典(具有不同的键)?

How to decode JSON dictionary (with varying keys) of dictionaries, using Codable?

我有以下简单的JSON:

{
    "201" :
    {
        "countryName" : "Albania",
        "countryCode" : "AL"
    },
    "202" :
    {
        "countryName" : "Andorra",
        "countryCode" : "AD"
    },
    ...
}

内部字典简单地变成:

struct Mid : Codable
{
    var countryName: String
    var countryCode: String
}

但后来我卡住了。我如何表示外部字典?

我想得到一个包含 Mid 个对象的字典,其中包含 String 个键 "201""202"、...

  • 简单的解决方案:

    • 解码[String:Mid]
  • 复杂的解决方案,如果你想要一个数组:

    • 作者:罗布·纳皮尔