Serde
Table of Contents
Framework for serialising and deserialising Rust data structures.
The de-facto standard in the Rust ecosystem. Format-agnostic —
serde itself provides the Serialize and Deserialize traits;
a companion crate handles the specific format (serde_json,
serde_yaml, bincode, etc.).
Related: Structs in Rust Traits in Rust Enums in Rust Rust
Setup
# Cargo.toml [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" serde_yaml = "0.9" # if needed bincode = "1.3" # if needed
Basic Usage
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
id: u32,
username: String,
is_active: bool,
}
fn main() {
let user = User { id: 1, username: "alice".to_string(), is_active: true };
// Serialize to JSON string
let json = serde_json::to_string_pretty(&user).unwrap();
println!("{}", json);
// Deserialize from JSON string
let parsed: User = serde_json::from_str(&json).unwrap();
println!("{:?}", parsed);
// Serialize/deserialize via file
let file = std::fs::File::create("user.json").unwrap();
serde_json::to_writer_pretty(file, &user).unwrap();
let file = std::fs::File::open("user.json").unwrap();
let from_file: User = serde_json::from_reader(file).unwrap();
}
Common Attributes
Serde attributes customise how fields and types are serialised/deserialised without changing the Rust type itself.
#[derive(Serialize, Deserialize, Debug)]
struct Config {
// Rename the field in the serialised output
#[serde(rename = "user_name")]
username: String,
// Skip this field entirely during serialisation
#[serde(skip)]
internal_state: String,
// Skip if the value is the type's default (e.g. false, 0, "")
#[serde(skip_serializing_if = "Option::is_none")]
optional_field: Option<String>,
// Provide a default value if the field is absent during deserialisation
#[serde(default)]
enabled: bool,
// Use a custom default function
#[serde(default = "default_port")]
port: u16,
}
fn default_port() -> u16 { 8080 }
Container-level attributes
// Rename all fields to camelCase (common for JSON APIs)
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ApiResponse {
user_id: u32, // serialised as "userId"
first_name: String, // serialised as "firstName"
}
// Deny unknown fields during deserialisation
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictConfig {
host: String,
port: u16,
}
// Flatten a nested struct into the parent
#[derive(Serialize, Deserialize)]
struct Response {
status: u16,
#[serde(flatten)]
data: UserData,
}
Enums
Serde has four representations for enums — the default (externally tagged) is most common for JSON:
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type", content = "data")] // adjacently tagged
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
// Adjacently tagged output:
// {"type": "Move", "data": {"x": 10, "y": 20}}
// vs externally tagged (default):
// {"Move": {"x": 10, "y": 20}}
// vs internally tagged:
// {"type": "Move", "x": 10, "y": 20}
// vs untagged:
// {"x": 10, "y": 20}
Format Comparison
| Format | Crate | Use case |
|---|---|---|
| JSON | serde_json |
APIs, config, human-readable |
| YAML | serde_yaml |
Config files (more expressive) |
| TOML | toml |
Rust-native config (Cargo.toml) |
| Bincode | bincode |
Fast binary serialisation |
| MessagePack | rmp-serde |
Compact binary, cross-language |
| CSV | csv (with serde feature) |
Tabular data |
Tips
- Derive macros handle 90% of use cases — reach for custom
Serialize=/=Deserializeimplementations only when behaviour needs to diverge significantly from the struct definition rename_all = "camelCase"is the most common container attribute when working with JavaScript/JSON APIsskip_serializing_if = "Option::is_none"keeps JSON output clean by omitting null fields rather than writingnullflattenis useful for spreading a nested config struct into a single JSON object without changing the Rust type hierarchy- For error handling prefer
serde_json::from_str::<T>()with?over.unwrap()in production code — deserialization errors should surface cleanly, not panic