如何使用Serde使用自定义函数反序列化可选字段?

时间:2017-06-01 07:57:05

标签: json serialization rust serde

我想使用自定义函数序列化和反序列化chrono::NaiveDate,但Serde书籍不包含此功能,代码文档也没有帮助。

#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
extern crate chrono;

use chrono::NaiveDate;


mod date_serde {
    use chrono::NaiveDate;
    use serde::{self, Deserialize, Serializer, Deserializer};

    pub fn serialize<S>(date: &Option<NaiveDate>, s: S) -> Result<S::Ok, S::Error>
    where S: Serializer {
        if let Some(ref d) = *date {
            return s.serialize_str(&d.format("%Y-%m-%d").to_string())
        }
        s.serialize_none()
    }

    pub fn deserialize<'de, D>(deserializer: D)
        -> Result<Option<NaiveDate>, D::Error>
        where D: Deserializer<'de> {
        let s: Option<String> = Option::deserialize(deserializer)?;
        if let Some(s) = s {
            return Ok(Some(NaiveDate::parse_from_str(&s, "%Y-%m-%d").map_err(serde::de::Error::custom)?))
        }

        Ok(None)
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct Test {
    pub i: u64,
    #[serde(with = "date_serde")]
    pub date: Option<NaiveDate>,
}

fn main() {
    let mut test: Test = serde_json::from_str(r#"{"i": 3, "date": "2015-02-03"}"#).unwrap();
    assert_eq!(test.i, 3);
    assert_eq!(test.date, Some(NaiveDate::from_ymd(2015, 02, 03)));
    test = serde_json::from_str(r#"{"i": 5}"#).unwrap();
    assert_eq!(test.i, 5);
    assert_eq!(test.date, None);
}

我知道Serde可以很容易地将Option<chrono::NaiveDate>反序列化,因为Chrono有Serde支持,但是我试图学习Serde所以我想自己实现它。当我运行此代码时出现错误:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ErrorImpl { code: Message("missing field `date`"), line: 1, column: 8 }', /checkout/src/libcore/result.rs:859
note: Run with `RUST_BACKTRACE=1` for a backtrace.

1 个答案:

答案 0 :(得分:10)

struct deserialization的默认行为是在字段不以序列化形式出现时为其分配各自的默认值。请注意,这与container #[serde(default)] attribute不同,后者使用结构的默认值填充字段。

#[derive(Debug, PartialEq, Deserialize)]
pub struct Foo<'a> {
    x: Option<&'a str>,
}

let foo: Foo = serde_json::from_str("{}")?;
assert_eq!(foo, Foo { x: None });

但是,当我们使用另一个反序列化函数(#[serde(deserialize_with = "path")])时,此规则会更改。此处Option类型的字段不再告诉解串器该字段可能不存在。相反,它表明存在可能为空或无效内容的字段(Serde术语中为none)。例如,在serde_json中,Option<String>是等效于&#34的JavaScript; nullstring&#34; (TypeScript / Flow表示法中的null | string)。下面的代码适用于给定的定义和日期反序列化器:

let test: Test = serde_json::from_str(r#"{"i": 5, "date": null}"#)?;
assert_eq!(test.i, 5);
assert_eq!(test.date, None);

幸运的是,通过添加serde(default)属性(Option::default产生None),反序列化过程可以变得更加宽松:

#[derive(Debug, Serialize, Deserialize)]
struct Test {
    pub i: u64,

    #[serde(default)]
    #[serde(with = "date_serde")]
    pub date: Option<NaiveDate>,
}

Playground

另见: