将 Codable/Encodable 转换为 JSON 对象 swift

Converting Codable/Encodable to JSON object swift

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

extension Encodable {

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

这很好用,但有没有更好的方法来实现同样的效果?

我的建议是将函数命名为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
    }
}

使用此扩展将可编码对象转换为 JSON 字符串:

extension Encodable {
    /// Converting object to postable JSON
    func toJSON(_ encoder: JSONEncoder = JSONEncoder()) throws -> NSString {
        let data = try encoder.encode(self)
        let result = String(decoding: data, as: UTF8.self)
        return NSString(string: result)
    }
}