1

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

Azurlake
  • 612
  • 1
  • 6
  • 29
  • 1
    It's not Alamofire, it's `Foundation.JSONEncoder` & `Encodable` behavior. See https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder – Larme Nov 09 '22 at 11:04
  • Indeed, thanks for pointing that out, I already implemented something like it's suggested on that issue and it worked. Feel free to move the comment to a "proper" (with all due respect) answer and I'll accept it, thanks again! – Azurlake Nov 09 '22 at 11:41
  • 1
    Does this answer your question? [Encode nil value as null with JSONEncoder](https://stackoverflow.com/questions/47266862/encode-nil-value-as-null-with-jsonencoder) – Larme Nov 09 '22 at 12:01

0 Answers0