RRust By Example
intermediateSerialization

Serde Basics

Serialize and deserialize with serde attributes.

Serde Basics

Serialize and deserialize with serde attributes.

Difficulty

Intermediate

Code

rust
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    name: String,
    #[serde(default)]
    version: String,
    debug: bool,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let json = r#"{"name":"myapp","debug":true}"#;
    let config: Config = serde_json::from_str(json)?;
    println!("parsed: {:?}", config);

    let output = serde_json::to_string_pretty(&config)?;
    println!("serialized:\n{}", output);
    Ok(())
}

Explanation

Serde attributes customize serialization: default, rename, skip.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the serialization category to build a complete understanding of this topic.

More Serialization Examples