使用 serde 将 RFC-3339 时间戳(反)序列化为 time-rs OffsetDateTime

Mth*_*enn 4 rfc3339 rust serde

我的目标是使用serdetime-rs将具有RFC-3339时间戳的对象从 Json 序列化为 Rust 结构(反之亦然)。

我希望这...

use serde::Deserialize;
use time::{OffsetDateTime};

#[derive(Deserialize)]
pub struct DtoTest {
    pub timestamp: OffsetDateTime,
}

fn main() {
    let deserialization_result = serde_json::from_str::<DtoTest>("{\"timestamp\": \"2022-07-08T09:10:11Z\"}");
    let dto = deserialization_result.expect("This should not panic");
    println!("{}", dto.timestamp);
}
Run Code Online (Sandbox Code Playgroud)

...创建结构并将时间戳显示为输出,但我得到...

thread 'main' panicked at 'This should not panic: Error("invalid type: string \"2022-07-08T09:10:11Z\", expected an `OffsetDateTime`", line: 1, column: 36)', src/main.rs:12:38
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Run Code Online (Sandbox Code Playgroud)

我的依赖项如下所示:

[dependencies]
serde = { version = "1.0.138", features = ["derive"] }
serde_json = "1.0.82"
time = { version = "0.3.11", features = ["serde"] }
Run Code Online (Sandbox Code Playgroud)

根据time-rs crate 的文档,这似乎是可能的,但我一定错过了一些东西。

Cha*_*man 9

默认的序列化格式time是某种内部格式。如果您想要其他格式,您应该启用该serde-well-known功能并使用该serde模块选择您想要的格式:

#[derive(Deserialize)]
pub struct DtoTest {
    #[serde(with = "time::serde::rfc3339")]
    pub timestamp: OffsetDateTime,
}
Run Code Online (Sandbox Code Playgroud)