微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我目前正在使用此扩展程序,该扩展程序适用于基本对象。我很难弄清楚如何通过此调用将嵌套的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] }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。