So I have an API route that returns a JSON array of objects. For example:
[
{\"firstname\": \"Tom\", \"lastname\": \"Smith\", \"age\": 31},
{\"firstname\
I managed to serialize data response to codable objects.
As all you may have been familiar with converting json object [String: String]
for example. That json object need to be converted to Data
by using json.data(using: .utf8)!
.
With Alamofire, it is easy to get that data (or at least this kind of data worked for me, already compatible with .utf8
thing), I can just use this already available function
func responseData(queue: DispatchQueue?, completionHandler: @escaping (DataResponse) -> Void) -> Self
Then just use that data as input for the Decoder
in the completionHandler
let objek = try JSONDecoder().decode(T.self, from: data)
You can also make this to some generic serialization function, with a little tweak, from the documentation
Generic Response Object Serialization
to this modification
func responseCodable(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse) -> Void)
-> Self
{
let responseSerializer = DataResponseSerializer { request, response, data, error in
guard error == nil else { return .failure(BackendError.network(error: error!)) }
guard let data = data else {
return .failure(BackendError.objectSerialization(reason: "data is not valid"))
}
do{
let objek = try JSONDecoder().decode(T.self, from: data!)
return .success(objek)
} catch let e {
return .failure(BackendError.codableSerialization(error: e))
}
}
return response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
}
Sample struct
struct Fids: Codable {
var Status: Status?
var Airport: Airport?
var Record: [FidsRecord]
}
Use the function this way
Alamofire.request("http://whatever.com/zzz").responseCodable { (response: DataResponse) in
switch response.result{
case .success(let value):
print(value.Airport)
// MARK: do whatever you want
case .failure(let error):
print(error)
self.showToast(message: error.localizedDescription)
}
}