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

Swift 在动态类型/对象上使用Codable,swift,swift4,codable,Swift,Swift4,Codable,嗨,我在一个更大的结构中嵌套了以下结构,该结构是从api调用返回的,但我无法对这部分进行编码/解码。我遇到的问题是customKey和customValue都是动态的 { "current" : "a value" "hash" : "some value" "values": { "customkey": "customValue", "customKey": "customValue" } } 我尝试了类似于var-value

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

{
    "current" : "a value"
    "hash" : "some value"
    "values": {
        "customkey": "customValue",
        "customKey": "customValue"
    }
}

我尝试了类似于
var-values:[String:String]
的方法,但这显然不起作用,因为它实际上不是
[String:String]

的数组,因为您链接到了我对另一个问题的答案,我将扩展该答案以回答您的问题

事实是,如果您知道在何处查找,则所有密钥在运行时都是已知的:

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)
        }
    }
}
用法:

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)

简单回答,它正在使用字典[String:String](instatead of String您可以使用其他结构):


@瓦迪安,我看不出这些问题有什么重复之处。我现在修改了问题以使其更加清晰。我理解并重新打开了问题:简短回答:您不能将
Codable
与动态键一起使用。您能推荐另一种方法吗?如果键是动态的,您只能使用动态集合类型,在本例中是一本字典。你有没有关于如何将它与字典一起使用的示例?非常感谢你的快速回复。如果JSON中的其他键位于正常可解码的值旁边,那么这将如何应用?我是否为此添加了正常的枚举容器?我对您的新要求感到困惑。你能编辑JSON来展示一个例子吗?我编辑了JSON。我的意思是,我正在编码和解码的实际对象不只是值key->object.:)@CodeDifferent我的情况类似,但就我而言,我知道“key1”和“key2”,但不知道“值”,我不知道如何调整你的代码,你能帮忙吗?谢谢@TmSmth这里没有足够的信息让我帮忙。请发布一个新问题,详细说明您的具体情况
let jsonData = """
{
    "current": "a value",
    "hash": "a value",
    "values": {
        "key1": "customValue",
        "key2": "customValue"
    }
}
""".data(using: .utf8)!

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

let model = try JSONDecoder().decode(MyModel.self, from: jsonData)

for (key,value) in model.values {
    print("key: \(key) value: \(value)")
}