我从外部 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)'
最佳答案
对 DateTime
的序列化进行抽象可以使用 TimestampMilliSeconds
输入来自 serde_with
.
有了它,您可以从浮点数、整数或字符串序列化/反序列化。您需要启用 chrono
serde_with
的功能.
第一个参数(此处为 String
)配置序列化行为。如果是 String
这意味着 DateTime
将被序列化为包含以毫秒为单位的 Unix 时间戳的字符串。
第二个参数(此处为 Flexible
)允许配置反序列化行为。 Flexible
意味着它将从浮点数、整数和字符串反序列化而不返回错误。您可以使用它来获取 main
函数从问题运行。另一个选项是 Strict
,它只反序列化第一个参数的格式。对于此示例,这意味着它只会将时间反序列化为字符串,但在遇到整数时会返回错误。
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
}
关于rust - 使用 serde 从字符串毫秒时间戳反序列化 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61831962/