【问题标题】:Decode an optional Dictionary without actual mapping in Swift 4在 Swift 4 中解码没有实际映射的可选字典
【发布时间】:2017-10-26 13:38:12
【问题描述】:

我有一个包含[String: Any]? 类型的可选元数据字段的结构。我想将 JSON 解析为该结构,并明确不映射字典,而是保持原样。

struct MyObject: Decodable {
    let id: String
    let whatever: String
    let metaData: [String: Any]?

    enum CardKeys: String, CodingKey {
        case id
        case whatever
        case metaData
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CardKeys.self)
        id = try container.decode(String.self, forKey: .id)
        whatever = try container.decode(String.self, forKey: .whatever)
        metaData = try container.decodeIfPresent([String: Any].self, forKey: .metaData)
    }
}

该代码编译并启动,但在运行时失败。我猜[String: Any] 不是我可以在这里使用的有效类型。但是那我该怎么做呢?

【问题讨论】:

标签: swift dictionary codable


【解决方案1】:

我创建了一个框架来解码/编码字典。

CodableDictionary

安装框架并替换

  let metaData: [String: Any]?

  let metaData: CodableDictionary?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多