examples/serialize-deserialize-with-serde/Cargo.toml
[package]
name = "serialize-deserialize-with-serde"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde = { version = "1.0.199", features = ["derive"] }
serde_json = "1.0.116"
examples/serialize-deserialize-with-serde/src/main.rs
use std::error::Error;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
enum Animal {
#[serde(default="cat")]
Cat,
Dog,
}
#[derive(Serialize, Deserialize)]
struct Pet {
name: String,
class: Animal,
}
fn main() -> Result<(), Box<dyn Error>> {
let my_dog = Pet {
name: String::from("Chewy"),
class: Animal::Dog,
};
let my_cat = Pet {
name: String::from("Kitty"),
class: Animal::Cat,
};
println!("{}", serde_json::to_string_pretty(&my_dog)?);
println!("{}", serde_json::to_string_pretty(&my_cat)?);
Ok(())
}