Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Codable/Encodable to JSON object swift

Recently i incorporated Codable in a project and to get a JSON object from a type conforming to Encodable i came up with this extension,

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
    }
}

This works well but could there be any better way to achieve the same?

like image 296
Kamran Avatar asked Dec 12 '25 06:12

Kamran


1 Answers

My suggestion is to name the function toDictionary and hand over possible errors to the caller. A conditional downcast failure (type mismatch) is thrown wrapped in an typeMismatch Decoding error.

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)
        if let json = object as? [String: Any]  { return json }
        
        let context = DecodingError.Context(codingPath: [], debugDescription: "Deserialized object is not a dictionary")
        throw DecodingError.typeMismatch(type(of: object), context)
    }
}
like image 109
vadian Avatar answered Dec 14 '25 05:12

vadian