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