我有示例 A
对象,它应该是 Decodable
:
class A: Decodable {
class B: Decodable {
let value: Int
}
let name: Date
let array: [B]
}
然后我有 Decoder
对象的 ADecoder
子类:
class ADecoder: Decoder {
let data: [String: Any]
// Keyed decoding
public func container<Key>(keyedBy type: Key.Type)
throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
return KeyedDecodingContainer(AKeyedDecoding(data))
}
// ...
}
它使用AKeyedDecoding
键控解码容器:
class AKeyedDecoding<T: CodingKey> : KeyedDecodingContainerProtocol {
typealias Key = T
let data: [String: Any]
func decode<T>(_ type: T.Type, forKey key: Key)
throws -> T where T: Decodable {
if type == Date.self {
// Parse date, for example
}
// Not called:
if type == Array<Decodable>.self {
// Decode array of `Decodable`s
}
}
// Rest of protocol implementations...
}
解码过程:
let values = ["name": "Hello" as AnyObject, "array": ["value": 2] as AnyObject]
let decoder = ADecoder(data: values)
do {
try A(from: decoder)
} catch {
print(error)
}
这适用于具有自定义 Date
数据类型的 name
字段。
但我无法解码 B
对象数组。
有人知道如何实现它或从哪里获得更多信息吗?
- 如何检查
T.type
是否是Decodable
的Array
? - 如何解码它们?
最佳答案
对于数组,您需要提供 unkeyedContainer()方法,用于解码位置容器中的值。
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
}
请注意,您还需要提供 singleValueContainer()用于解码叶子(最深的属性级别)。
func singleValueContainer() throws -> SingleValueDecodingContainer {
}
关于swift - KeyedDecodingContainer 解码内部 Decodable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49134932/