使用带有`Option<chrono::DateTime>`的`serde::Serialize`

尝试序列化时Option<chrono::DateTime<Utc>>遇到错误:

error[E0308]: mismatched types
  --> src/main.rs:39:14
   |
39 |     #[derive(Serialize, Debug)]
   |              ^^^^^^^^^ expected struct `DateTime`, found enum `std::option::Option`
   |
   = note: expected reference `&DateTime<Utc>`
              found reference `&'__a std::option::Option<DateTime<Utc>>`
   = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0308]: mismatched types
  --> src/main.rs:39:14
   |
39 |     #[derive(Serialize, Debug)]
   |              ^^^^^^^^^ expected struct `DateTime`, found enum `std::option::Option`
   |
   = note: expected reference `&DateTime<Utc>`
              found reference `&'__a std::option::Option<DateTime<Utc>>`
   = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)

代码(游乐场):

看着chrono::ts_seconds和serde_with我不知道该往哪里前进。

我真的很感激这方面的任何帮助。

回答

Chrono 已经有一个功能Option<DateTime<Utc>>,即chrono::serde::ts_seconds_option

#[derive(Serialize, Debug)]
struct TestStruct {
    pub a: f32,
    #[serde(with = "ts_seconds_option")]
    pub date: Option<DateTime<Utc>>,
}

解决方案serde_with如下:

#[serde_as]
#[derive(Serialize, Debug)]
struct TestStruct {
    pub a: f32,
    #[serde_as(as = "Option<DurationSeconds<i64>>")]
    pub date: Option<DateTime<Utc>>,
}


以上是使用带有`Option&lt;chrono::DateTime&gt;`的`serde::Serialize`的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>