KeyedDecodingContainer解码内部可解码对象

时间:2018-03-06 15:51:13

标签: swift swift4 decodable

我有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 Decodable的{​​{1}}是否为public class Icom : ICommand { public ViewM VieM { get; set; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } public Icom(ViewM view) { this.VieM = view; } public bool CanExecute(object parameter) { Repository R = (Repository)parameter; if (R != null) { if (string.IsNullOrEmpty(R.ID) || (string.IsNullOrEmpty(R.Name))) return false; return true; } return false; } public void Execute(object parameter) { VieM.Wy(); } }
  • 如何解码它们?

1 个答案:

答案 0 :(得分:1)

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

func unkeyedContainer() throws -> UnkeyedDecodingContainer {
}

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

func singleValueContainer() throws -> SingleValueDecodingContainer {
}