无法从 json 反序列化 chrono::DateTime

Unable to deserialize chrono::DateTime from json

我遇到一个有趣的问题。由于某种原因,serde 无法以与序列化相同的格式从字符串中反序列化 chrono::DateTime<Utc> 对象(但如果我用它保存变量,它会这样做):

use chrono; // 0.4.11
use serde_json; // 1.0.48

fn main() {
    let date = chrono::Utc::now();
    println!("{}", date);

    let date_str = serde_json::to_string(&date).unwrap();
    println!("{}", date_str);

    let parsed_date: chrono::DateTime<chrono::Utc> = serde_json::from_str(&date_str).unwrap();
    println!("{}", parsed_date);

    assert_eq!(date, parsed_date);

    let date = "2020-03-28T16:29:04.644008111Z";
    let _: chrono::DateTime<chrono::Utc> = serde_json::from_str(&date).unwrap();
}

这是playground link

输出:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.01s
     Running `target/debug/playground`
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error("invalid type: integer `2020`, expected a formatted date and time string or a unix timestamp", line: 1, column: 4)', src/main.rs:17:44
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Standard Output

2020-03-28 17:57:04.222452521 UTC
"2020-03-28T17:57:04.222452521Z"
2020-03-28 17:57:04.222452521 UTC

为什么会这样?我应该怎么做?

你需要输入有效的json,不要忘记双引号:

let date = "\"2020-03-28T16:29:04.644008111Z\"";

println!("{:?}", date_str);

可以看到