swift - KeyedDecodingContainer 解码内部 Decodable 对象

标签 swift swift4 decodable

我有示例 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 是否是DecodableArray
  • 如何解码它们?

最佳答案

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

func unkeyedContainer() throws -> UnkeyedDecodingContainer {
}

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

func singleValueContainer() throws -> SingleValueDecodingContainer {
}

关于swift - KeyedDecodingContainer 解码内部 Decodable 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49134932/

相关文章:

ios - 是否可以在 iPad Split View Controller 中插入标题?

arrays - 如何过滤包含字符串的数组和结构体对象数组,其中有字符串参数?

ios - 在 Objective-C 项目中使用 Swift 静态库时出错

ios - 如何在键是动态的 Swift 4 中为 JSON 编写 Decodable?

json - 为什么我没有使用 Decodable 获取 JSON?

ios - 协议(protocol)扩展中的默认值

SwiftUI:NavigationBar 和 TabBar 的全屏 View

swift - 为什么在 Swift 类中使用必需的初始化器?

ios - JavaScript 无法在 iOS 的 WKWebView 中工作

ios - 如何从 iOS Swift Codable 中的 API 响应通知或打印模型类上缺少的键?