如何对 chrono::Duration 进行序列化和反序列化?

4
在我目前的项目中,我试图在配置结构体中存储一个chrono::Duration,并且偶尔使用serde_json进行序列化和反序列化。不幸的是,SerializeDeserialize 没有为chrono::Duration实现。不过,chrono表示它通过其可选功能之一支持serde。我尝试使用此方法,但现在编译器正在抱怨返回方法:
error[E0308]: mismatched types
 --> src/config.rs:6:10
  |
6 | #[derive(Serialize, Deserialize, Debug, Clone)]
  |          ^^^^^^^^^ expected struct `DateTime`, found struct `chrono::Duration`
  |
  = note: expected reference `&DateTime<Utc>`
         found reference `&'__a chrono::Duration`
  = note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0308]: mismatched types
 --> src/config.rs:6:21
  |
6 | #[derive(Serialize, Deserialize, Debug, Clone)]
  |                     ^^^^^^^^^^^ expected struct `chrono::Duration`, found struct `DateTime`
  |
  = note: expected struct `chrono::Duration`
             found struct `DateTime<Utc>`
  = note: this error originates in the macro `try` (in Nightly builds, run with -Z macro-backtrace for more info)

为什么会发生这种情况?我该怎么解决它?

以下是相关代码:

use serde::{Serialize, Deserialize};
use chrono::{DateTime, Duration, Utc};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    pub dest_ip: String,
    #[serde(borrow)]
    pub include_paths: Vec<&'static std::path::Path>,
    pub exclude_paths: Vec<&'static std::path::Path>,
    #[serde(with = "chrono::serde::ts_seconds")]
    pub time_between_checks: Duration,
}

此外,这是 Cargo.toml 的相关部分:
serde_json = "1.0.72"
serde = { version = "1.0.130", features = ["derive"] }
chrono = { version = "0.4.19", features = ["serde"]}

1
请查看2017年的这个问题 https://github.com/chronotope/chrono/issues/117 - Stargateur
1
ts_seconds 仅适用于 DateTime 实例。 - Jmb
1个回答

8
您可以使用serde_with::DurationSeconds进行序列化。它与ts_seconds完全相同,但支持更多类型和序列化形式。
#[serde_with::serde_as]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    // ...
    #[serde_as(as = "serde_with::DurationSeconds<i64>")]
    pub time_between_checks: Duration,
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接