Skip to content

Instantly share code, notes, and snippets.

@ilantoren
Created November 16, 2021 08:34
Show Gist options
  • Save ilantoren/0c91dcc7457ea0724db8f38eb31aadb1 to your computer and use it in GitHub Desktop.
Save ilantoren/0c91dcc7457ea0724db8f38eb31aadb1 to your computer and use it in GitHub Desktop.
serde as used in Rocket
/**
For a web server objects are sent serialized into json, but a client
could create an object from the http call response
**/
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(crate = "rocket::serde")]
pub struct Restaurant {
cuisine: String,
borough: String,
name: String,
address: Address,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(crate = "rocket::serde")]
pub struct Address {
building: String,
street: String,
zipcode: String,
}
// Convert Restaurant objects to an user friendly string
impl fmt::Display for Restaurant {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "place: {} cuisine: {} location: {} {}", self.name, self.cuisine, self.borough, self.address)
}
}
// for serialization into JSON
impl Into<Document> for Restaurant {
fn into(self) -> Document {
doc!{ "name": self.name, "cuisine": self.cuisine, "borough": self.borough, "building": self.address.building, "street": self.address.street}
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}, {} ", self.building, self.street, self.zipcode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment