CodeBlanks Logo Icon CodeBlanks

Serialize and Deserialize

Learn serde's core Serialize and Deserialize traits.

Serialize and Deserialize

serde is the standard way to convert Rust data structures to formats like JSON, TOML and YAML (serialization) and read them back (deserialization). It's built on two traits: Serialize and Deserialize. Formats are separate crates: serde_json, toml, serde_yaml.

// Cargo.toml
// serde = { version = "1", features = ["derive"] }
// serde_json = "1"
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Kitap {
    ad: String,
    yil: u16,
}
// {"ad":"Dune","yil":1965}

Serializing by hand

Since there are no external crates in the exercises, we'll write serialization by hand; this is essentially what the derive generates behind the scenes. Text fields go in quotes, numbers are written as they are:

impl Kitap {
    fn json(&self) -> String {
        format!("{{\"ad\":\"{}\",\"yil\":{}}}", self.ad, self.yil)
    }
}

Inside format!, braces are written as {{ and }}, quotes as \". Real serde also escapes special characters in the text.

Practice Book to JSON

Write the json method above for Kitap { ad: String, yil: u16 }. Print the result for Kitap { ad: "Dune".into(), yil: 1965 }.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
struct Kitap {
    ad: String,
    yil: u16,
}

impl Kitap {
    fn json(&self) -> String {
        format!("{{\"ad\":\"{}\",\"yil\":{}}}", self.ad, self.yil)
    }
}

fn main() {
    let k = Kitap { ad: "Dune".into(), yil: 1965 };
    println!("{}", k.json());
}

Expected output

{"ad":"Dune","yil":1965}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the benefit of serde separating the data structure from the format?

  • It only supports JSON
  • The same struct can be used with JSON, TOML or another format unchanged Correct answer
  • Smaller files
  • It provides encryption

Explanation: The struct only says "how to walk it"; the format crate turns that into text.

2 Writing trait

Question
#[derive(____, Deserialize)]
struct Kitap {
    ad: String,
}
Answer
#[derive(Serialize, Deserialize)]
struct Kitap {
    ad: String,
}

Explanation: Serialize makes it possible to write the value to a format.

3 Concept and meaning

Term Meaning
Serialize Data → format
Deserialize Format → data
serde_json JSON format
{{ and }} (format!) Escaped braces

All lessons in Intermediate