使用 serde 从字符串毫秒时间戳反序列化 DateTime

Deserializing a DateTime from a string millisecond timestamp with serde

我从外部 API 收到一个毫秒时间戳作为 JSON 字符串属性。

{"time":"1526522699918"}

使用 Serde 将毫秒时间戳解析为字符串的最佳方法是什么?

ts_milliseconds 选项将毫秒时间戳作为整数处理,但在使用字符串时会抛出错误。

示例 - Rust Playground

#[macro_use]
extern crate serde_derive;
extern crate chrono;
use chrono::serde::ts_milliseconds;
use chrono::{DateTime, Utc};

#[derive(Deserialize, Serialize)]
struct S {
    #[serde(with = "ts_milliseconds")]
    time: DateTime<Utc>,
}

fn main() {
    serde_json::from_str::<S>(r#"{"time":1526522699918}"#).unwrap(); // millisecond timestamp as a integer
    serde_json::from_str::<S>(r#"{"time":"1526522699918"}"#).unwrap(); // millisecond timestamp as an string
}

错误信息:

Error("invalid type: string \"1526522699918\", expected a unix timestamp in milliseconds", line: 1, column: 23)'

可以使用 serde_with 中的 TimestampMilliSeconds 类型对 DateTime 的序列化 for 进行抽象。 使用它,您可以序列化为浮点数、整数或字符串/反序列化。您需要为 serde_with.

启用 chrono 功能

第一个参数(此处为 String)配置序列化行为。在 String 的情况下,这意味着 DateTime 将被序列化为包含以毫秒为单位的 Unix 时间戳的字符串。

第二个参数(这里是 Flexible)允许配置反序列化行为。 Flexible 意味着它将从浮点数、整数和字符串反序列化而不会 returning 错误。您可以使用它来将 main 函数从问题中获取到 运行。另一个选项是 Strict,它只反序列化第一个参数的格式。对于此示例,这意味着它只会将时间反序列化为字符串,但在遇到整数时会 return 出错。

use ::chrono::{DateTime, Utc};
use serde_with::TimestampMilliSeconds;
use serde_with::formats::Flexible;

#[serde_with::serde_as]
#[derive(serde::Deserialize, serde::Serialize)]
struct S {
    #[serde_as(as = "TimestampMilliSeconds<String, Flexible>")]
    time: DateTime<Utc>,
}

fn main() {
    serde_json::from_str::<S>(r#"{"time":1526522699918}"#).unwrap(); // millisecond timestamp as a integer
    serde_json::from_str::<S>(r#"{"time":"1526522699918"}"#).unwrap(); // millisecond timestamp as an string
}