}"#; let got: Record = serde_json::from_str(&json)?; assert_eq!(got.timestamp, Timestamp::from_second(1517644800)?); assert_eq!(serde_json::to_string(&got)?, json); # Ok::<(), Box>(()) ``` # Example: optional timestamp support And this example shows how to use an `Option` instead of a `Timestamp`. Note that in this case, we show how to roundtrip the number of **milliseconds** since the Unix epoch: ``` use jiff::Timestamp; #[derive(Debug, serde::Deserialize, serde::Serialize)] struct Record { #[serde(with = "jiff::fmt::serde::timestamp::millisecond::optional")] timestamp: Option, } let json = r#"{"timestamp":1517644800123}"#; let got: Record = serde_json::from_str(&json)?; assert_eq!(got.timestamp, Some(Timestamp::from_millisecond(1517644800_123)?)); assert_eq!(serde_json::to_string(&got)?, json); # Ok::<(), Box>(()) ``` # Example: the "friendly" duration format The [`Span`](crate::Span) and [`SignedDuration`](crate::SignedDuration) types in this crate both implement Serde's `Serialize` and `Deserialize` traits. For `Serialize`, they both use the [ISO 8601 Temporal duration format], but for `Deserialize`, they both support the ISO 8601 Temporal duration format and the ["friendly" duration format] simultaneously. In order to serialize either type in the "friendly" format, you can either define your own serialization functions or use one of the convenience routines provided by this module. For example: ``` use jiff::{ToSpan, Span}; #[derive(Debug, serde::Deserialize, serde::Serialize)] struct Record { #[serde( serialize_with = "jiff::fmt::serde::span::friendly::compact::required" )] span: Span, } let json = r#"{"span":"1 year 2 months 36 hours 1100ms"}"#; let got: Record = serde_json::from_str(&json)?; assert_eq!( got.span, 1.year().months(2).hours(36).milliseconds(1100).fieldwise(), ); let expected = r#"{"span":"1y 2mo 36h 1100ms"}"#; assert_eq!(serde_json::to_string(&got).unwrap(), expected); # Ok::<(), Box>(()) ``` [Serde]: https://serde.rs/ [`with` attribute]: https://serde.rs/field-attrs.html#with [`serialize_with` attribute]: https://serde.rs/field-attrs.html#serialize_with [ISO 8601 Temporal duration format]: crate::fmt::temporal ["friendly" duration format]: crate::fmt::friendly