#chrono #deserialize #duration #serde-json #ext #features #seconds

serde-duration-ext

Serde support for std::time::Duration and chrono::Duration (chrono feature)

1 unstable release

0.1.0 Feb 9, 2024

#1403 in Encoding

Download history 8/week @ 2024-07-30 1/week @ 2024-08-06 2/week @ 2024-08-13 1/week @ 2024-08-27 16/week @ 2024-09-03 15/week @ 2024-09-10 1/week @ 2024-09-17 18/week @ 2024-09-24 21/week @ 2024-10-01 24/week @ 2024-10-08 35/week @ 2024-10-15 70/week @ 2024-10-22 2/week @ 2024-10-29

133 downloads per month

Custom license

19KB
364 lines

Serde support for Duration and chrono::Duration

Installation

Add the following to your Cargo.toml:

[dependencies]
serde_duration_ext = "0.1.0"

Also you can enable the chrono feature to support chrono::Duration

[dependencies]
serde_duration_ext = { version = "0.1.0", features = ["chrono"] }

Usage

use serde::{Serialize, Deserialize};
use serde_json;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Foo {
    #[serde(with = "serde_duration_ext")]
    duration: std::time::Duration,
}

fn main() {
    let foo = Foo {
        duration: std::time::Duration::from_secs(123),
    };
    let json = serde_json::to_string(&foo).unwrap();
    assert_eq!(json, r#"{"duration":"123s"}"#);

    let foo2: Foo = serde_json::from_str(&json).unwrap();
    assert_eq!(foo, foo2);
}

You can also use chrono::Duration if you enable the chrono feature.

use serde::{Serialize, Deserialize};
use serde_json;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Foo {
    #[serde(with = "serde_duration_ext::chrono")]
    duration: chrono::Duration,
}

fn main() {
    let foo = Foo {
        duration: chrono::Duration::seconds(123),
    };
    let json = serde_json::to_string(&foo).unwrap();
    assert_eq!(json, r#"{"duration":"123s"}"#);

    let foo2: Foo = serde_json::from_str(&json).unwrap();
    assert_eq!(foo, foo2);
}

Library also provides useful types such as DurationUnit and TimeUnit

use serde::{Serialize, Deserialize};
use serde_json;

use serde_duration_ext::DurationUnit;

#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct Foo {
    duration: DurationUnit,
}

fn main() {
    let foo = Foo {
        duration: DurationUnit::from_secs(123),
    };
    let json = serde_json::to_string(&foo).unwrap();
    assert_eq!(json, r#"{"duration":"123s"}"#);

    let foo2: Foo = serde_json::from_str(&json).unwrap();
    assert_eq!(foo, foo2);
}

Dependencies

~2.2–3.5MB
~65K SLoC