Otbivnoe / CodableAlamofire

An extension for Alamofire that converts JSON data into Decodable objects.
MIT License
740 stars 55 forks source link

JSONDecoder.dateDecodingStrategy not working for custom format #11

Open Dino4674 opened 5 years ago

Dino4674 commented 5 years ago

When using this DateFormatter separately, I can successfully deserialize date string with it:

extension DateFormatter {
    static let apiDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        //2019-08-05T08:41:06.590Z
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        return formatter
    }()
}

If I use the same formatter when calling .responeDecodableObject(decoder: decoder), model properties (of Date type) are set to nil.

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(.apiDateFormatter)

Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers)
    .responseDecodableObject(decoder: decoder) { (response: DataResponse<T>) in
        let data = response.data
}

Is there any more setup that I am not aware of? Thanks

Dino4674 commented 5 years ago

I also tried deserializing date by using JSONDecoder with custom formatter and it works. Here is a sample code:


        struct AB: Codable {
            let date: Date?
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .formatted(.apiDateFormatter)

        let data = "{ \"date\": \"2019-08-05T08:41:06.590Z\" }".data(using: .utf8)
        let object = try? decoder.decode(AB.self, from: data!)

        print("Object: \(object)")

From this it looks like I've been configuring up JSONDecoder correctly and that the problem is in CodableAlamofire library when using this decoder.