I'm using Alamofire 5.6.2 with the following JSON encoder:
let encoder = JSONParameterEncoder.json()
encoder.encoder.dateEncodingStrategy = .formatted(DateFormatter.standard)
encoder.encoder.keyEncodingStrategy = .convertToSnakeCase
And then using it in a POST request like this:
let headers: HTTPHeaders = [
.authorization(bearerToken: token),
.accept("application/json"),
.contentType("application/json;charset=UTF-8"),
.acceptEncoding("utf-8")
]
AF.request(path, method: .post, parameters: data, encoder: encoder, headers: headers).validate().responseDecodable(of: R.self, decoder: decoder) { response in
switch response.result {
...
}
The data
parameter is an object like the following:
struct SampleRequest: Codable {
var param1: Bool
var param2: Float?
}
And the problem is, if param2
is nil, the key won't be added to the request body. This is a problem for me since the endpoint I'm targeting uses the same request flow for different update tasks, and it needs to know if a particular key is nil in order to set it as null in the backend, or it's not present and hence it shouldn't do anything with it.
I can't find any options on the JSONParameterEncoder.json()
encoder I'm using in order to keep the keys when the value is nil. How could this be accomplished?
Thanks in advance