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

Rust 使用serde从字符串毫秒时间戳反序列化DateTime,rust,serde,Rust,Serde,我从外部API接收毫秒时间戳作为JSON字符串属性 {"time":"1526522699918"} 使用Serde将毫秒时间戳解析为字符串的最佳方法是什么 ts_millides选项将毫秒时间戳作为整数使用,但在使用字符串时会引发错误 示例- #[宏使用] 外部板条箱serde_; 外部板条箱时钟; 使用chrono::serde::ts_毫秒; 使用chrono::{DateTime,Utc}; #[派生(反序列化、序列化)] 结构{ #[serde(with=“ts_毫秒”)] 时间:日

我从外部API接收毫秒时间戳作为JSON字符串属性

{"time":"1526522699918"}
使用Serde将毫秒时间戳解析为字符串的最佳方法是什么

ts_millides
选项将毫秒时间戳作为整数使用,但在使用字符串时会引发错误

示例-

#[宏使用]
外部板条箱serde_;
外部板条箱时钟;
使用chrono::serde::ts_毫秒;
使用chrono::{DateTime,Utc};
#[派生(反序列化、序列化)]
结构{
#[serde(with=“ts_毫秒”)]
时间:日期时间,
}
fn main(){
serde_json::from_str::(r#“{”time:1526522699918}”).unwrap();//毫秒时间戳为整数
serde_json::from_str::(r#“{”time:“1526522699918}”).unwrap();//毫秒时间戳作为字符串
}
错误消息:

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

可以使用
serde_中的
timestampilless
类型对
DateTime
的序列化进行抽象。 使用它,您可以从浮点、整数或字符串进行序列化/反序列化。您需要启用
serde_with
chrono
功能

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

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

use::chrono::{DateTime,Utc};
将serde_与::timestampells一起使用;
将serde_与::formats::Flexible一起使用;
#[serde_with::serde_as]
#[派生(serde::反序列化,serde::序列化)]
结构{
#[serde_as(as=“timestamps”)]
时间:日期时间,
}
fn main(){
serde_json::from_str::(r#“{”time:1526522699918}”).unwrap();//毫秒时间戳为整数
serde_json::from_str::(r#“{”time:“1526522699918}”).unwrap();//毫秒时间戳作为字符串
}
请参见