简体   繁体   English

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

[英]How to serialize and deserialize chrono::Duration?

In my current project I'm trying to store a chrono::Duration in a configuration struct, which will be serialized and deserialized occasionally using serde_json .在我当前的项目中,我试图将chrono::Duration存储在配置结构中,偶尔会使用serde_json对其进行序列化和反序列化。

Unfortunately, it appears that Serialize and Deserialize aren't implemented for chrono::Duration .不幸的是,似乎没有为chrono::Duration实现SerializeDeserialize That said, chrono says it has support for serde via one of its optional features.也就是说, chrono表示它通过其可选功能之一支持serde I tried using this method, but now the compiler is complaining about return methods:我尝试使用这种方法,但现在编译器抱怨返回方法:

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)

Why is this happening?为什么会这样? What can I do to fix it?我能做些什么来修复它?

Here's the code in question:这是有问题的代码:

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,
}

Also, here's the relevant bits of Cargo.toml:另外,这里是 Cargo.toml 的相关部分:

serde_json = "1.0.72"
serde = { version = "1.0.130", features = ["derive"] }
chrono = { version = "0.4.19", features = ["serde"]}

You can use serde_with::DurationSeconds for serialization.您可以使用serde_with::DurationSeconds进行序列化。 It works identical to ts_seconds but supports more types and serialization forms.它的工作原理与ts_seconds相同,但支持更多类型和序列化 forms。

#[serde_with::serde_as]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    // ...
    #[serde_as(as = "serde_with::DurationSeconds<i64>")]
    pub time_between_checks: Duration,
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM