我从外部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)'