Skip to content
This repository has been archived by the owner on Nov 8, 2021. It is now read-only.

JSONDecoder.dateDecodingStrategy not working for custom format #11

Open
Dino4674 opened this issue Aug 8, 2019 · 1 comment
Open

JSONDecoder.dateDecodingStrategy not working for custom format #11

Dino4674 opened this issue Aug 8, 2019 · 1 comment

Comments

@Dino4674
Copy link

Dino4674 commented Aug 8, 2019

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
Copy link
Author

Dino4674 commented Aug 8, 2019

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant