将Codable / Encodable转换为JSON对象swift

时间:2018-10-22 05:26:25

标签: ios swift codable encodable

最近我将Codable合并到一个项目中,并从符合JSON的类型中获取Encodable对象,我想出了这个扩展名,

extension Encodable {

    /// Converting object to postable JSON
    func toJSON(_ encoder: JSONEncoder = JSONEncoder()) -> [String: Any] {
        guard let data = try? encoder.encode(self) else { return [:] }
        guard let object = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { return [:] }
        guard let json = object as? [String: Any] else { return [:] }
        return json
    }
}

这很好,但是有没有更好的方法可以达到相同目的呢?我感觉到频繁jsonObject(with:具有较大data的对象的调用gridster可能会有性能问题。

1 个答案:

答案 0 :(得分:1)

我的建议是命名函数toDictionary并将可能的错误移交给调用方。有条件的向下失败(类型不匹配)被包装在typeMismatch de 编码错误中。

extension Encodable {

    /// Converting object to postable dictionary
    func toDictionary(_ encoder: JSONEncoder = JSONEncoder()) throws -> [String: Any] {
        let data = try encoder.encode(self)
        let object = try JSONSerialization.jsonObject(with: data)
        guard let json = object as? [String: Any] else {
            let context = DecodingError.Context(codingPath: [], debugDescription: "Deserialized object is not a dictionary")
            throw DecodingError.typeMismatch(type(of: object), context)
        }
        return json
    }
}