Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created February 4, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/dce00614f8f188e850d7a7e96e897fa3 to your computer and use it in GitHub Desktop.
Save rust-play/dce00614f8f188e850d7a7e96e897fa3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
extern crate chrono;
extern crate serde;
extern crate serde_json;
use serde::{Serialize, Deserialize};
use chrono::{Utc, DateTime}; // 0.4.6
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
z: Option<i32>,
#[serde(with = "my_date_format")]
w: DateTime<Utc>,
}
fn main() {
let points = vec![
Point { x: 1, y: 2, z: None, w: Utc::now() },
Point { x: 10, y: 20, z: Some(30), w: Utc::now() },
];
let serializeds = points.iter()
.map(|point| {
let s = serde_json::to_string(point).unwrap();
println!("Serialized: {}", s);
s
});
/*
.map(|spoint| {
let d = serde_json::from_str(spoint).unwrap();
println!("Deserialized: {}", d);
d
});
*/
println!("{:?}", serializeds);
/*
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
*/
}
mod my_date_format {
use chrono::{DateTime, Utc, TimeZone};
use serde::{self, Deserialize, Serializer, Deserializer};
const FORMAT: &'static str = "%Y-%m-%d %H:%M:%S";
// The signature of a serialize_with function must follow the pattern:
//
// fn serialize<S>(&T, S) -> Result<S::Ok, S::Error> where S: Serializer
//
// although it may also be generic over the input types T.
pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let s = format!("{}", date.format(FORMAT));
serializer.serialize_str(&s)
}
// The signature of a deserialize_with function must follow the pattern:
//
// fn deserialize<D>(D) -> Result<T, D::Error> where D: Deserializer
//
// although it may also be generic over the output types T.
pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Utc.datetime_from_str(&s, FORMAT).map_err(serde::de::Error::custom)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment