小编Emr*_*mre的帖子

如何将自定义 serde 解串器用于计时时间戳?

我正在尝试将 JSON 解析为一个具有chrono::DateTime字段的结构。JSON 以自定义格式保存时间戳,我为其编写了反序列化器。

我如何连接两者并使用它来工作#[serde(deserialize_with)]

我正在使用NaiveDateTime更简单的代码

extern crate serde;
extern crate serde_json;
use serde::Deserialize;
extern crate chrono;
use chrono::NaiveDateTime;

fn from_timestamp(time: &String) -> NaiveDateTime {
    NaiveDateTime::parse_from_str(time, "%Y-%m-%dT%H:%M:%S.%f").unwrap()
}

#[derive(Deserialize, Debug)]
struct MyJson {
    name: String,
    #[serde(deserialize_with = "from_timestamp")]
    timestamp: NaiveDateTime,
}

fn main() {
    let result: MyJson =
        serde_json::from_str(r#"{"name": "asdf", "timestamp": "2019-08-15T17:41:18.106108"}"#)
            .unwrap();
    println!("{:?}", result);
}
Run Code Online (Sandbox Code Playgroud)

我收到三个不同的编译错误:

error[E0308]: mismatched types
  --> src/main.rs:11:10
   |
11 | #[derive(Deserialize, Debug)]
   |          ^^^^^^^^^^^ expected reference, found type parameter …
Run Code Online (Sandbox Code Playgroud)

rust rust-chrono serde

9
推荐指数
2
解决办法
3681
查看次数

标签 统计

rust ×1

rust-chrono ×1

serde ×1