如何使带有`variable: [String: Codable]` 的结构可编码?

How to make a struct with `variable: [String: Codable]` 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 
}

纠结了好久。 有人知道如何解决吗?

您可以使用一些库,例如 AnyCodable

然后你可以使用 AnyCodable class 而不是 Any 来使你的结构 Codable。

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"])])