Rust
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.
Exercise Book to JSON
Write the json method above for Kitap { ad: String, yil: u16 }. Print the result for Kitap { ad: "Dune".into(), yil: 1965 }.
Show example solution
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());
}
Test yourself
-
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
- Smaller files
- It provides encryption
Show answer
The same struct can be used with JSON, TOML or another format unchanged — The struct only says "how to walk it"; the format crate turns that into text.
-
Writing trait
#[derive(____, Deserialize)]
struct Kitap {
ad: String,
}
Show answer
#[derive(Serialize, Deserialize)]
struct Kitap {
ad: String,
}
-
Concept and meaning
- Serialize
- Data → format
- Deserialize
- Format → data
- serde_json
- JSON format
- {{ and }} (format!)
- Escaped braces
Next lesson: derive