13

我正在尝试将 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);
}

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

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<_, _>`

我很确定该from_timestamp函数返回的是DateTimestruct 而不是 a Result,所以我不知道“预期的 struct chrono::NaiveDateTime,找到的 enum std::result::Result”可能意味着什么。

4

2 回答 2

11

虽然@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

于 2019-08-23T09:25:05.017 回答
10

这相当复杂,但以下工作:

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);
}
于 2019-08-22T18:35:05.703 回答