如何序列化和反序列化 chrono::Duration?

The*_*eks 4 rust rust-chrono serde

在我当前的项目中,我尝试将 a 存储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)
Run Code Online (Sandbox Code Playgroud)

为什么会发生这种情况?我能做什么来修复它?

这是有问题的代码:

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)
Run Code Online (Sandbox Code Playgroud)

另外,这是 Cargo.toml 的相关部分:

serde_json = "1.0.72"
serde = { version = "1.0.130", features = ["derive"] }
chrono = { version = "0.4.19", features = ["serde"]}
Run Code Online (Sandbox Code Playgroud)

jon*_*sbb 9

您可以用于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,
}
Run Code Online (Sandbox Code Playgroud)