This works, but in my case, the field could have a null value, and I'm not sure how to change the example to work with Option<DateTime<Utc>> instead.
So in general, my question is, if I have a way to deserialize a field to a type T, is there a straightforward way to reuse that to deserialize a field to type Option<T>?
I won't operate on chrono directly, as I will admit it's easier for me to test ideas in playpen. That said, this should be possible to do with chrono too.
But, now a custom deserialization for i32 is needed to handle Option<i32>. It's possible to provide a wrapper type to deal with this issue. I will just change definition of S struct here to refer to a single field struct.
The access to that field now requires unpacking (Some(WrappedI32(value)) => ...,) or using .0 syntax. There are ways to avoid this, but they are uglier (involving writing a deserializer callback function for Option<_>).
Thanks! I was hoping there was a way to do it without needing to resort to using a newtype as the final output -- normally I'd be fine with it if the containing struct were part of some internal interface, but unfortunately I intend for it to be in the public-facing part of a library. It would be a bit cumbersome for users to have to deal with a wrapper type (when the existence of the wrapper is just an implementation detail around how the data was deserialized).
I'll continue to think about it, but thanks for the answer! I might just end up going that route if I can't find another way to do it.
Ok, your example is the same =)
But if you remove "s2": null from &str you will get error about missing value. You must put #[serde(default)] before #[serde(deserialize_with = "callback_opt")], so no transparent solution =(