【问题标题】:How to make a struct with `variable: [String: Codable]` codable?如何使具有`variable:[String:Codable]`的结构可编码?
【发布时间】:2021-03-30 11:44:51
【问题描述】:

我得到了一个类似下面的结构

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 
}

我挣扎了好久???? 有人知道如何解决吗?

【问题讨论】:

  • 你可以使用枚举类型而不是 Any 但我认为这样的小姐 json 需要一个通常的序列化而不是编码

标签: swift codable


【解决方案1】:

你可以使用像AnyCodable这样的库

然后您可以使用 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"])])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    相关资源
    最近更新 更多