首页 > 解决方案 > 根目录下的 Codable Handle 动态键

问题描述

我已经看过几个类似的问题,但我有不同的 JSON

所以我的 JSON 如下所示

var json = """
{
"Array1": [
{
"FinancialYear": "17-18"

}],
"Array2": [
{
"FinancialYear": "17-18"
}]
}
"""

问题是Array1Array2键,它们似乎是动态的,它位于 ROOT 并且可能更像 Array3、Array4 等

我想使用 Codable 但由于根 (Array1,Array2) 的动态键我无法摆脱它。

这是我尝试过但不工作的结构

struct CodableJSON: Codable {
    var response:[String:[ArrayInside]]
    enum CodingKeys: String, CodingKey   {
        case response = "What should I write here ?" // What should be here ? 
    }

}

标签: iosswiftcodable

解决方案


在这种情况下,只声明ArrayInside结构

struct ArrayInside: Decodable {
   ...
}

并将根对象解码为字典

let result = try JSONDecoder().decode([String:[ArrayInside]].self, from: data)

推荐阅读