如何将自定义Serde反序列化器用于chrono时间戳

时间:2019-08-22 17:41:06

标签: rust serde rust-chrono

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

如何连接两者并使用#[serde(deserialize_with)]使它正常工作?

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

extern crate serde_json;      
extern crate serde;      
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);
}

我遇到了三种不同的编译错误:

error[E0308]: mismatched types
  --> src/main.rs:11:10
   |
11 | #[derive(Deserialize, Debug)]
   |          ^^^^^^^^^^^ expected reference, found type parameter
   |
   = note: expected type `&std::string::String`
              found type `__D`

error[E0308]: mismatched types
  --> src/main.rs:11:10
   |
11 | #[derive(Deserialize, Debug)]
   |          ^^^^^^^^^^-
   |          |         |
   |          |         this match expression has type `chrono::NaiveDateTime`
   |          expected struct `chrono::NaiveDateTime`, found enum `std::result::Result`
   |          in this macro invocation
   |
   = note: expected type `chrono::NaiveDateTime`
              found type `std::result::Result<_, _>`

error[E0308]: mismatched types
  --> src/main.rs:11:10
   |
11 | #[derive(Deserialize, Debug)]
   |          ^^^^^^^^^^-
   |          |         |
   |          |         this match expression has type `chrono::NaiveDateTime`
   |          expected struct `chrono::NaiveDateTime`, found enum `std::result::Result`
   |          in this macro invocation
   |
   = note: expected type `chrono::NaiveDateTime`
              found type `std::result::Result<_, _>`

error: aborting due to 3 previous errors

For more information about this error, try `rustc --explain E0308`.
error: Could not compile `testcrate`.

To learn more, run the command again with --verbose.

我非常确定from_timestamp函数返回的是DateTime结构而不是Result,所以我不知道找到了什么“预期结构chrono::NaiveDateTime”枚举std::result::Result”的意思。

2 个答案:

答案 0 :(得分:2)

这相当复杂,但是可以起作用:

use chrono::NaiveDateTime;
use serde::de;
use serde::Deserialize;
use std::fmt;

struct NaiveDateTimeVisitor;

impl<'de> de::Visitor<'de> for NaiveDateTimeVisitor {
    type Value = NaiveDateTime;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a string represents chrono::NaiveDateTime")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        match NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S.%f") {
            Ok(t) => Ok(t),
            Err(_) => Err(de::Error::invalid_value(de::Unexpected::Str(s), &self)),
        }
    }
}

fn from_timestamp<'de, D>(d: D) -> Result<NaiveDateTime, D::Error>
where
    D: de::Deserializer<'de>,
{
    d.deserialize_str(NaiveDateTimeVisitor)
}

#[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);
}

答案 1 :(得分:2)

@edwardw的回答在技术上是正确的,因为恕我直言,其中包含太多样板。

NaiveDataTime实现FromStr,这意味着您可以编写可重用的通用解串器功能。

一个令人费解的示例-确实在JSON中添加了表示为字符串的age字段(u8)。只是为了证明您可以将其用于实现FromStr的任何事物。

use std::fmt::Display;
use std::str::FromStr;

use chrono::NaiveDateTime;
use serde::{de, Deserialize, Deserializer};

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

// You can use this deserializer for any type that implements FromStr
// and the FromStr::Err implements Display
fn deserialize_from_str<'de, S, D>(deserializer: D) -> Result<S, D::Error>
where
    S: FromStr,      // Required for S::from_str...
    S::Err: Display, // Required for .map_err(de::Error::custom)
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    S::from_str(&s).map_err(de::Error::custom)
}

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

如果要指定格式(使用NaiveDateTime::parse_from_str),则更加容易:

use chrono::NaiveDateTime;
use serde::{de, Deserialize, Deserializer};

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

fn naive_date_time_from_str<'de, D>(deserializer: D) -> Result<NaiveDateTime, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = Deserialize::deserialize(deserializer)?;
    NaiveDateTime::parse_from_str(&s, "%Y-%m-%dT%H:%M:%S.%f").map_err(de::Error::custom)
}

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

#[serde(deserialize_with = "path")]文档:

  

使用与其实现Deserialize不同的函数反序列化此字段。给定函数必须可调用为fn<'de, D>(D) -> Result<T, D::Error> where D: Deserializer<'de>,尽管它在T上也可以通用。与deserialize_with一起使用的字段不需要实现Deserialize