Skip to content

Rust Serialization — JSON and Serde for Data Serialization and Deserialization

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust Serialization. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust serde framework provides derive macros for Serialize and Deserialize traits with JSON, YAML, and custom format support via serde_json, serde_yaml.

What You'll Learn

  • Serde derive macros
  • JSON serialization
  • Custom field mapping
  • Nested serialization

Why It Matters

Serde is the standard Rust serialization framework. DodaZIP uses serde for configuration and metadata JSON. Almost every Rust project uses serde.

Real-World Use

API responses, configuration files, data storage, network protocols.

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)]
struct User {
    name: String,
    age: u8,
    #[serde(rename = "emailAddr")]
    email: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    phone: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    server: ServerConfig,
    database: DatabaseConfig,
}

#[derive(Serialize, Deserialize, Debug)]
struct ServerConfig {
    host: String,
    port: u16,
}

#[derive(Serialize, Deserialize, Debug)]
struct DatabaseConfig {
    url: String,
    pool_size: u32,
}

fn main() -> Result<(), serde_json::Error> {
    let user = User {
        name: "Alice".to_string(),
        age: 30,
        email: "alice@example.com".to_string(),
        phone: None,
    };

    // Serialize to JSON
    let json = serde_json::to_string_pretty(&user)?;
    println!("JSON:\n{}", json);

    // Deserialize from JSON
    let json_str = r#"{"name":"Bob","age":25,"emailAddr":"bob@test.com"}"#;
    let user: User = serde_json::from_str(json_str)?;
    println!("User: {:?}", user);

    // Parse dynamic JSON
    let value: serde_json::Value = serde_json::from_str(
        r#"{"name":"Charlie","age":35}"#
    )?;
    println!("Name: {}", value["name"]);
    println!("Age: {}", value["age"]);

    Ok(())
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro