chrono::serde::ts_milliseconds_option

Function deserialize

Source
pub fn deserialize<'de, D>(d: D) -> Result<Option<DateTime<Utc>>, D::Error>
where D: Deserializer<'de>,
Expand description

Deserialize a DateTime from a millisecond timestamp or none

Intended for use with serdes deserialize_with attribute.

ยงExample:

use chrono::serde::ts_milliseconds_option::deserialize as from_milli_tsopt;

#[derive(Deserialize, PartialEq, Debug)]
#[serde(untagged)]
enum E<T> {
    V(T),
}

#[derive(Deserialize, PartialEq, Debug)]
struct S {
    #[serde(default, deserialize_with = "from_milli_tsopt")]
    time: Option<DateTime<Utc>>,
}

let my_s: E<S> = serde_json::from_str(r#"{ "time": 1526522699918 }"#)?;
assert_eq!(my_s, E::V(S { time: Some(Utc.timestamp_opt(1526522699, 918000000).unwrap()) }));
let s: E<S> = serde_json::from_str(r#"{ "time": null }"#)?;
assert_eq!(s, E::V(S { time: None }));
let t: E<S> = serde_json::from_str(r#"{}"#)?;
assert_eq!(t, E::V(S { time: None }));