【问题标题】:Unable to deserialize chrono::DateTime from json无法从 json 反序列化 chrono::DateTime
【发布时间】:2020-03-28 16:56:31
【问题描述】:

我遇到了一个有趣的问题。由于某种原因,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 rust chrono serde


    【解决方案1】:

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

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

    您可以通过println!("{:?}", date_str);查看它

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多