首页 > 解决方案 > 使用 `serde::Serialize` 和 `Option`

问题描述

尝试序列化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)

代码(游乐场):

use chrono::{serde::ts_seconds, DateTime, NaiveDate, Utc};
use serde::Serialize;

fn main() {
    let test_struct = TestStruct {
        a: 2.45,
        date: Some(DateTime::from_utc(
            NaiveDate::from_ymd(2000, 1, 1).and_hms(1, 1, 1),
            Utc,
        )),
    };
    let string = serde_json::to_string(&test_struct).unwrap();
    println!("default: {}", string);
    
    #[derive(Serialize, Debug)]
    struct TestStruct {
        pub a: f32,
        #[serde(with = "ts_seconds")]
        pub date: Option<DateTime<Utc>>,
    }
}

看着chrono::ts_secondsserde_with我不知道在哪里继续前进。

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

标签: datetimerustserde

解决方案


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

推荐阅读