Decoding dates with dateDecodingStrategy

I had a question about date deserialization. If a container (or its sub-containers) has dates in multiple formats, is the best way to go about it to decode a string and then run each one through a custom date formatter?

It seems strange to me that dateDecodingStrategy is a top-level decoder concern rather than being part of an individual date decode method. In my custom init(from decoder: Decoder) methods, I want to put the knowledge in there instead of relying on something from outside to set it correctly. Maybe I am missing something?

Thanks as always for any insights you can share with me.

Ray

1 Like

Ray,

For now, my strategy to date decoding is configuring

<code>
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = JSONDecoder.DateDecodingStrategy.custom({
foo -> Date in
let container = try foo.singleValueContainer()
let dateStr = try container.decode(String.self)
return myCustomDateParse(dateStr)
})
</code>

···

2017-10-23 2:24 GMT-02:00 Ray Fix via swift-users <swift-users@swift.org>:

I had a question about date deserialization. If a container (or its
sub-containers) has dates in multiple formats, is the best way to go about
it to decode a string and then run each one through a custom date formatter?

It seems strange to me that dateDecodingStrategy is a top-level decoder
concern rather than being part of an individual date decode method. In my
custom init(from decoder: Decoder) methods, I want to put the knowledge in
there instead of relying on something from outside to set it correctly.
Maybe I am missing something?

Thanks as always for any insights you can share with me.

Ray
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

--
"o animal satisfeito dorme". - Guimarães Rosa