Skip to content

Instantly share code, notes, and snippets.

Created June 1, 2017 09:15
Show Gist options
  • Save anonymous/aafc3231eb25328776d876199561cb37 to your computer and use it in GitHub Desktop.
Save anonymous/aafc3231eb25328776d876199561cb37 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
#[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(default)]
#[serde(with = "date_serde")]
pub date: Option<NaiveDate>,
}
fn main() {
let 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)));
let test: Test = serde_json::from_str(r#"{"i": 5, "date": null}"#).unwrap();
assert_eq!(test.i, 5);
assert_eq!(test.date, None);
let test: Test = serde_json::from_str(r#"{"i": 7}"#).unwrap();
assert_eq!(test.i, 7);
assert_eq!(test.date, None);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment