【问题标题】:KeyedDecodingContainer decode inner Decodable objectsKeyedDecodingContainer 解码内部可解码对象
【发布时间】:2018-03-06 15:51:13
【问题描述】:

我有示例 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)
}

这适用于具有自定义 Date 数据类型的 name 字段。 但我一直在解码 B 对象的数组。

有人知道如何实现它或从哪里获得更多信息?

  • 如何检查T.type 是否是ArrayDecodables?
  • 如何解码?

【问题讨论】:

    标签: swift swift4 decodable


    【解决方案1】:

    对于数组,您需要提供unkeyedContainer() 方法,用于解码位置容器中的值。

    func unkeyedContainer() throws -> UnkeyedDecodingContainer {
    }
    

    请注意,您还需要提供singleValueContainer() 来解码叶子(最深的属性级别)。

    func singleValueContainer() throws -> SingleValueDecodingContainer {
    }
    

    【讨论】:

    • 这个方法的实现只是为了抛出一个错误,但它们并没有被调用。对于键B,它仍然调用decode&lt;T&gt;(_ type: T.Type, forKey key: Key),类型=Array&lt;B&gt;。是否只有覆盖 init(from:) 并为特定字段手动获取 unkeyed/singelValue 容器的方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    相关资源
    最近更新 更多