我正在从我的JSON REST API检索一个复杂的嵌套对象。
DocumentDraft
- uuid: String
- schema: Schema // Very complicated object with many variations
- url: String
- values: [Value]
- successors: [String]
- predecessors: [String]
Value
- key: String
- val: String? OR [String]? // <-- This is the problem我认为解决这个问题的正确方法是引入泛型类型。
struct Value<V: Decodable>: Decodable {
let key: String
let val: V?
}..。但即便如此,values可能是一个混合数组,所以我看不出声明V是什么会有什么帮助。
但是,当然,泛型类型在层次结构中一直向上传播,到DocumentDraft对象,到发布者,到我的应用程序接口调用,等等,污染了整个链,否则非常干净和可读的调用和对象。我只想在Value级别上处理这个问题,让JSONDecoder以某种方式简单地返回两者中的一个。
有没有其他方法可以在不更改整个父对象的情况下将可选val作为String或[String]来处理?
发布于 2020-08-19 20:31:07
只需使用[String]类型,手动实现Decodable协议的init(from:)函数即可实现,如下所示:
struct Value: Decodable {
let key: String
let val: [String]?
enum CodingKeys: String, CodingKey {
case key, val
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
key = try container.decode(String.self, forKey: .key)
do {
if let string = try container.decodeIfPresent(String.self, forKey: .val) {
val = [string]
} else {
val = nil
}
} catch DecodingError.typeMismatch {
val = try container.decodeIfPresent([String].self, forKey: .val)
}
}
}当解码为String值成功时,创建一个只有一个元素的字符串数组。当解码到String值失败时,尝试解码为[String]
https://stackoverflow.com/questions/63486641
复制相似问题