0

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

1 回答 1

1

我不确定嵌套字典是什么意思,但看起来你不想返回字典数组。我认为你正在寻找的是一个字典,它的值是字典。无论如何,我将发布两个选项:

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] }
    }
}
于 2020-08-14T00:12:52.723 回答