Serialize and deserialize with serde

Rust

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(())
}

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo