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?
[String: Codable]
to your object to store keys that can change. Then you will only need JSONEncoder to convert object to json data. Use that data to prepare URLRequest and send it to Alamofire'srequest
method that takes URLRequestConvertible protocol – SpatolaCodable
andJSONSerialization
errors. Make the functionthrow
, remove the question marks aftertry
and hand over the error to the caller. – Arbil