How to Use serde for Any Data Format in Rust

Use the serde crate with the derive feature to automatically serialize and deserialize Rust structs into formats like JSON or TOML.

Use the serde crate with the derive feature to automatically implement serialization and deserialization for any data format supported by a Serde ecosystem crate like serde_json or toml.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
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();
    let parsed: Config = serde_json::from_str(&json).unwrap();
}

Add serde = { version = "1.0", features = ["derive"] } and serde_json = "1" to your Cargo.toml dependencies.