RRust By Example
intermediateSerialization

JSON with Serde

Serialize and deserialize JSON with serde_json.

JSON with Serde

Serialize and deserialize JSON with serde_json.

Difficulty

Intermediate

Code

rust
use serde::{Deserialize, Serialize};

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

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = Config {
        name: "myapp".into(),
        version: "1.0.0".into(),
        debug: true,
    };

    let json = serde_json::to_string_pretty(&config)?;
    println!("{}", json);

    let parsed: Config = serde_json::from_str(&json)?;
    println!("{:?}", parsed);

    Ok(())
}

Explanation

Serde serializes/deserializes with #[derive(Serialize, Deserialize)].

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