默认情况下,chrono::DateTime不支持serde的序列化与反序列化。
但可以通过向chrono添加名为serde的features来对其进行序列化与反序列化,自动序列化为时间戳以及从时间戳反序列化。
首先在Cargo.toml中添加features:
TOML
chrono = { version = "0.4", features = ["serde"] }
然后引入对应的序列化模块:
RUST
use chrono::serde::ts_seconds; // 秒级时间戳
use chrono::serde::ts_milliseconds; // 毫秒时间戳
use chrono::serde::ts_nanoseconds; // 纳秒时间戳
// 上面三个模块名后面加上_option则为可选类型(Option<DateTime<Utc>>)
然后对对应字段添加serde的注解:
RUST
#[derive(Serialize, Deserialize)]
pub struct Entity {
#[serde(with = "ts_seconds")] //其中ts_seconds就是上面引入的模块名
pub gmt_create: DateTime<Utc>,
}
之后当进行序列化时,自动把DateTime转换为i64类型的秒级时间戳,反序列化则相反。
当然也可以自己编写序列化器的模块,可参考chrono::serde::ts_seconds
的代码,并将注解中的with的值改为自己编写的序列化器的模块名即可。