time
time copied to clipboard
`well-known` serde for `Vec<OffsetDateTime>`
I am porting my program from chrono
to time
. One thing I am stuck with is serializing a Vec<OffsetDateTime>
with the rfc3339
format.
This seems like a small but very useful addition. Is this something that would be considered to be included?
This is what just tried to use in the serialize_with
attribute:
fn date_vec_ser<S: Serializer>(
vec: &[OffsetDateTime],
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
let stringvec = vec
.iter()
.map(|odt| odt.format(&Rfc3339))
.collect::<std::result::Result<Vec<String>, time::error::Format>>()
.map_err(S::Error::custom)?;
stringvec.serialize(serializer)
}
I'm not going to say it's 100%, but I think this is reasonable.
There is support for the well-known
formats in serde_with
, such that you can write this code and support other nestings.
#[serde_with::serde_as]
#[derive(Debug, serde::Deserialize)]
struct Data(
#[serde_as(as = "Vec<time::format_description::well_known::Rfc3339>")]
Vec<time::OffsetDateTime>
);
let v = serde_json::json!([
"1997-11-21T01:55:06-06:00",
"2000-01-21T05:55:06-06:00",
"2020-03-21T09:55:06-06:00",
"1997-11-21T23:55:06-06:00",
]);
let d: Data = serde_json::from_value(v).unwrap();
dbg!(d);