在动态类型/对象上使用Codable

Res*_*had 7 swift swift4 codable

嗨我有以下结构嵌套在一个更大的结构,从api调用返回,但我无法设法编码/解码这部分.我遇到的问题是customKey和customValue都是动态的.

{
    "current" : "a value"
    "hash" : "some value"
    "values": {
        "customkey": "customValue",
        "customKey": "customValue"
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了类似的东西var values: [String:String]但显然不起作用,因为它实际上并不是一个数组[String:String].

Cod*_*ent 10

既然你链接到我对另一个问题的答案,我会扩展那个问题来回答你的问题.

事实是,如果你知道在哪里看,所有的键在运行时都是已知的:

struct GenericCodingKeys: CodingKey {
    var intValue: Int?
    var stringValue: String

    init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
    init?(stringValue: String) { self.stringValue = stringValue }

    static func makeKey(name: String) -> GenericCodingKeys {
        return GenericCodingKeys(stringValue: name)!
    }
}


struct MyModel: Decodable {
    var current: String
    var hash: String
    var values: [String: String]

    private enum CodingKeys: String, CodingKey {
        case current
        case hash
        case values
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        current = try container.decode(String.self, forKey: .current)
        hash = try container.decode(String.self, forKey: .hash)

        values = [String: String]()
        let subContainer = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .values)
        for key in subContainer.allKeys {
            values[key.stringValue] = try subContainer.decode(String.self, forKey: key)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

let jsonData = """
{
    "current": "a value",
    "hash": "a value",
    "values": {
        "key1": "customValue",
        "key2": "customValue"
    }
}
""".data(using: .utf8)!

let model = try JSONDecoder().decode(MyModel.self, from: jsonData)
Run Code Online (Sandbox Code Playgroud)