How to use serde crate in Rust serialization

Use the serde crate with the derive feature to automatically serialize and deserialize Rust structs to JSON and other formats.

Add serde with the derive feature to your Cargo.toml and use the #[derive(Serialize, Deserialize)] macro on your structs to convert them to and from formats like JSON.

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[lib]
path = "src/lib.rs"
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Config {
    name: String,
    port: u16,
}

fn main() {
    let config = Config { name: "server".to_string(), port: 8080 };
    let json = serde_json::to_string(&config).unwrap();
    println!("{}", json);
}