【问题标题】:How to serialize and deserialize chrono::Duration?如何序列化和反序列化 chrono::Duration?
【发布时间】:2021-12-01 12:34:37
【问题描述】:

在我当前的项目中,我试图将chrono::Duration 存储在配置结构中,偶尔会使用serde_json 对其进行序列化和反序列化。

不幸的是,Serialize 和 Deserialize 似乎没有为 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"]}

【问题讨论】:

标签: rust chrono serde


【解决方案1】:

您可以使用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,
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-17
    • 2012-10-27
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多