How to Serialize and Deserialize JSON in Rust with Serde

Serialize and deserialize JSON in Rust by deriving serde traits on your structs and using serde_json functions.

Use the #[derive(serde::Deserialize)] and #[derive(serde::Serialize)] attributes on your structs to automatically implement JSON parsing and generation.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    output_mode: Mode,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Mode {
    Default,
    Simple,
}

let json = r#"{"output_mode": "simple"}"#;
let config: Config = serde_json::from_str(json).unwrap();
let output = serde_json::to_string(&config).unwrap();

This approach handles the conversion between JSON strings and Rust types, respecting naming conventions like snake_case or kebab-case via attributes.