Swift 如何使用'variable:[String:Codable]`Codable创建结构?

Swift 如何使用'variable:[String:Codable]`Codable创建结构?,swift,codable,Swift,Codable,我得到了一个如下的结构 struct Wrapper { var value: [String: Any] // type "Any" could be String, Int or [String]. // i.g. ["a": 1, "b": ["ccc"]] // and the keys of this dictionary are not determined } 我已经挣扎了很长

我得到了一个如下的结构

struct Wrapper {

  var value: [String: Any]
  // type "Any" could be String, Int or [String]. 
  // i.g. ["a": 1, "b": ["ccc"]]
  // and the keys of this dictionary are not determined 
}


我已经挣扎了很长一段时间你可以使用一些像

然后,您可以使用AnyCodable类而不是Any来使结构可编码

struct Wrapper: Codable {
    var value: [String: AnyCodable]
}
范例

let arrayWrapper: [String: Any] =
["value" :
       [
         "test" : ["1", "2", "3"],
         "parse" : ["4", "5", "6"]]
        ]

let jsonData = try! JSONSerialization.data(withJSONObject: arrayWrapper, options: .prettyPrinted)

do {
   let decoder = JSONDecoder()
   let result = try decoder.decode(Wrapper.self, from: jsonData)
   print("result:", result)
} catch let error {
   print("error:", error)
}

输出

result: Wrapper(value: ["parse": AnyCodable(["4", "5", "6"]), "test": AnyCodable(["1", "2", "3"])])

您可以使用枚举类型而不是任何类型,但我认为这样的missy json需要一个不可编码的常规序列化