快速将嵌套的可编码对象转换为字典

问题描述

我目前正在使用此扩展程序,该扩展程序适用于基本对象。我很难弄清楚如何通过此调用将嵌套的Codable对象转换为字典...预先感谢!

public extension encodable {
  var dictionary: [String: Any]? {
    guard let data = try? JSONEncoder().encode(self) else { return nil }
    return (try? JSONSerialization.jsonObject(with: data,options: .allowFragments)).flatMap { $0 as? [String: Any] }
  }
}

解决方法

我不确定嵌套词典是什么意思,但是您似乎不想返回一组词典。我认为您正在寻找的是一本字典,其中的值是字典。无论如何,我都会发布两个选项:

extension Encodable {
    // this would try to encode an encodable type and decode it into an a dictionary
    var dictionary: [String: Any] {
        guard let data = try? JSONEncoder().encode(self) else { return [:] }
        return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
    }
    // this would try to encode an encodable type and decode it into an array of dictionaries
    var dictionaries: [[String: Any]] {
        guard let data = try? JSONEncoder().encode(self) else { return [] }
        return (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] ?? []
    }
    // this would try to encode an encodable type and decode it into a dictionary with dictionaries as its value
    var nestedDictionaries: [String: [String: Any]] {
        guard let data = try? JSONEncoder().encode(self) else { return [:] }
        return (try? JSONSerialization.jsonObject(with: data)) as? [String: [String: Any]] ?? [:]
    }
    // this will return only the properties that are referring to a nested structure/classe
    var nestedDictionariesOnly: [String: [String: Any]] {
        guard let data = try? JSONEncoder().encode(self) else { return [:] }
        return ((try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]).compactMapValues { $0 as? [String:Any] }
    }
}