【发布时间】: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] 不是我可以在这里使用的有效类型。但是那我该怎么做呢?
【问题讨论】:
-
Decodable在设计时并未考虑到动态键。您可以解决它,但更好的方法是定义一个MyMetadata结构,其中包含所有可能的元数据作为可选属性
标签: swift dictionary codable