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?