我有示例A对象,应该是Decodable
class A: Decodable {
class B: Decodable {
let value: Int
}
let name: Date
let array: [B]
}然后,我有ADecoder子类的Decoder对象,用于:
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)
}这对于具有自定义name数据类型的Date字段来说很好。但是我被困在B对象阵列解码中了。
有人知道如何实施或从哪里获得更多的信息吗?
T.type是否是Array of Decodables?发布于 2018-03-06 18:49:45
对于数组,您需要提供一个unkeyedContainer()方法,该方法用于从位置容器中解码值。
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
}请注意,您还需要提供一个singleValueContainer()来解码leafs (最深属性级别)。
func singleValueContainer() throws -> SingleValueDecodingContainer {
}https://stackoverflow.com/questions/49134932
复制相似问题