datetime - 使用 `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_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>>,
}
推荐阅读
- javascript - 如何在 PayPal Javascript 代码中使用 PHP header() 函数
- google-cloud-platform - 我正在使用 GCP 服务帐户,但在调用 Dialog Flow API 时出现错误
- java - 如何从下拉列表中获取所选项目的 ID 并发送到 sqlite android?
- python - 使用自定义表单模板登录 Django
- python-3.x - 如何使用 numpy 生成多类测试数据集?
- reactjs - Reactjs API 调用大数据
- php - 如何在php中将图像文件转换为PDF文件?
- c# - 消费者生产者 - 生产者线程从不执行分配的功能
- azure - 无法在 Azure 上打开 WebDeploy 端口 (8172)
- reactjs - 如何在反应中唯一标识标签