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

serde-duration-ext

Serde对std::time::Duration和chrono::Duration的支持(chrono特性)

1个不稳定版本

0.1.0 2024年2月9日

#995 in 编码

自定义许可

19KB
364

Serde对Duration和chrono::Duration的支持

安装

将以下内容添加到您的Cargo.toml中

[dependencies]
serde_duration_ext = "0.1.0"

您还可以启用chrono特性以支持chrono::Duration

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

使用方法

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);
}

如果您启用了chrono特性,您还可以使用chrono::Duration

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);
}

库还提供了有用的类型,例如DurationUnitTimeUnit

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);
}

依赖项

~2.3–4MB
~66K SLoC