Skip to content
ImagineWorld

Serialization with Serde

node_idnode-book_oop-to-rust_chapter-24-serialization-with-serde
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num24
chapter_titleSerialization with Serde
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Littera scripta manet. (The written word remains.)

Serialization pervades modern software. Configuration files, network protocols, database storage, inter-process communication: all require converting structured data to bytes and back. Object-oriented languages typically address this through reflection, examining objects at runtime to discover their fields and types. Java’s Jackson library, C#‘s System.Text.Json, and similar frameworks introspect objects dynamically, building serialization logic on the fly or through runtime code generation.

Rust takes a different path. The serde crate (short for serialize/deserialize) uses Rust’s trait system and procedural macros to generate serialization code at compile time. No reflection, no runtime overhead, no surprises when a field rename breaks deserialization in production. The same derive macro that generates Debug implementations generates serialization logic, producing code as efficient as hand-written implementations while requiring only an attribute annotation.

Serde has become so fundamental to Rust development that understanding it is not optional. Configuration parsing, API clients, data pipelines, logging frameworks: serde appears everywhere. This chapter explains how serde works, how to use its derive macros effectively, and how to handle the edge cases that arise in real applications.

The Serde model

Serde separates two concerns that serialization frameworks often conflate: the data model and the data format. The data model describes what kinds of values can be serialized (integers, strings, sequences, maps, structs with named fields). The data format describes how those values become bytes (JSON, TOML, MessagePack, custom binary protocols). This separation allows any serializable type to work with any format without modification.

The architecture involves three participants. The data structure knows how to describe itself in terms of serde’s data model. The serializer knows how to convert data model primitives to a specific format. The deserializer knows how to parse a specific format back into data model primitives. Serde provides the traits that connect these participants; derive macros implement the traits for your types; format crates provide serializers and deserializers.

This design has profound implications. Adding support for a new format requires only implementing the serializer and deserializer traits. Every existing type that derives Serialize and Deserialize immediately works with the new format. Conversely, adding serialization support to a new type makes it compatible with every existing format. The combination multiplies rather than adds: M types times N formats produce M times N working combinations with no additional code.

The data model itself is richer than what most formats support directly. Serde distinguishes between structs (with named fields), tuple structs (with positional fields), newtype structs (single-field wrappers), and unit structs (no fields). It distinguishes between externally tagged, internally tagged, adjacently tagged, and untagged enum representations. Formats that cannot represent these distinctions natively receive guidance from serde about the intended structure, allowing reasonable mappings even when the format lacks direct support.

The following diagram illustrates serde’s architecture:

graph TD
    subgraph YT["Your Types"]
        C["Config"]
        U["User"]
        E["Event"]
    end
    subgraph ST["Serde Traits"]
        S["Serialize"]
        D["Deserialize"]
    end
    subgraph FC["Format Crates"]
        J["serde_json"]
        T["toml"]
        Y["serde_yaml"]
        B["bincode"]
    end
    YT --> S
    YT --> D
    S --> FC
    D --> FC

[!visual-conversion] Serde connects types to formats through shared traits. Print diagram (PDF 597, printed p. 587) of three stacked frames recreated in Mermaid; the print draws frame-to-frame arrows (Your Types → each trait → Format Crates), labels verbatim.

Deriving serialize and deserialize

The most common way to make a type serializable is deriving the Serialize and Deserialize traits. The derive macros examine the type’s structure and generate implementations that describe each field to serializers or reconstruct the type from deserializers. For developers coming from languages where serialization involves XML annotations, runtime reflection, or special base classes, the simplicity is striking. A single attribute annotation produces complete serialization support with zero runtime overhead.

The generated code is not merely adequate; it is optimal. The derive macro produces implementations equivalent to what an expert would write by hand, visiting each field in order and calling the appropriate serializer methods. Because code generation happens at compile time, the compiler can inline and optimize the serialization path just as it would hand-written code. Benchmarks consistently show serde matching or exceeding the performance of format-specific serialization libraries that do not use this abstracted approach.

use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct User {
id: u64,
username: String,
email: String,
active: bool,
}

This annotation generates code equivalent to manually implementing Serialize by calling the serializer’s methods for each field, and Deserialize by expecting fields in any order and constructing the struct when all required fields are present. The generated code handles missing fields, extra fields, and type mismatches according to the format’s conventions.

Enums serialize according to their representation. A simple enum without data becomes a string in most formats. An enum with variants carrying data uses one of several representations that serde supports. The default external tagging wraps the variant name and data in an object.

#[derive(Serialize, Deserialize, Debug)]
enum Status {
Active,
Suspended { reason: String },
Deleted,
}

The derive macros handle nested types automatically. A struct containing a Vec of other structs serializes by recursively serializing each element. Option fields serialize as null or absent depending on format conventions. Generic types work correctly when their type parameters implement the required traits.

The derive macros respect visibility but generate public trait implementations. A type with private fields can still derive Serialize and Deserialize; the generated code has access to private fields because it lives in the same module. This allows exposing serialization capability without exposing field access.

Common attributes

Serde’s derive macros accept attributes that customize serialization behavior. These attributes appear in three positions: on the type itself (container attributes), on enum variants (variant attributes), or on individual fields (field attributes). Understanding the common attributes covers most customization needs without requiring manual trait implementation.

Renaming fields

Field names in Rust follow snake_case convention. JSON APIs typically use camelCase. Configuration files might use kebab-case. Rather than forcing a choice between idiomatic Rust and format conventions, serde provides renaming attributes.

The rename attribute changes a single field’s serialized name:

#[derive(Serialize, Deserialize)]
struct ApiRequest {
#[serde(rename = "userId")]
user_id: u64,
#[serde(rename = "requestTime")]
request_time: String,
}

When all fields follow a consistent convention, rename_all on the container is cleaner:

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ApiRequest {
user_id: u64,
request_time: String,
}

Supported conventions include camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE, kebab-case, and SCREAMING-KEBAB-CASE. The attribute applies to all fields or variants without individual rename attributes.

Enum variants can be renamed similarly. An enum representing HTTP methods might use uppercase names in the format while keeping Rust’s conventions in code:

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
enum HttpMethod {
Get,
Post,
Put,
Delete,
}

Skipping and defaults

Not every field should be serialized. Cached computations, internal bookkeeping, or fields reconstructible from other data might deserve exclusion. The skip attribute omits a field entirely:

#[derive(Serialize, Deserialize)]
struct Document {
content: String,
#[serde(skip)]
cached_word_count: Option<usize>,
}

Skipped fields must implement Default for deserialization, since the deserializer will not provide a value. Alternatively, skip_serializing and skip_deserializing provide one-directional skipping when the field should participate in only one direction.

Fields that should use a default value when absent (but still serialize when present) use the default attribute:

#[derive(Serialize, Deserialize)]
struct Settings {
theme: String,
#[serde(default)]
font_size: u32, // Uses Default::default() (0) when absent
#[serde(default = "default_language")]
language: String,
}
fn default_language() -> String {
"en".to_string()
}

The default attribute without arguments calls Default::default(). With a path argument, it calls the specified function. This allows sensible defaults that differ from the type’s default implementation.

Combining skip and default enables versioning strategies. Adding a new field with both skip_serializing_if and default maintains backward compatibility: old data deserializes correctly using the default, while new data includes the field only when meaningful.

#[derive(Serialize, Deserialize)]
struct Config {
name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
new_feature: Option<FeatureConfig>,
}

Flattening and adjacently tagged enums

Some data structures do not map directly to serde’s default representation. A struct might logically include all fields from another struct without nesting. An enum might need its tag and content in separate sibling fields rather than nested objects. Serde provides attributes for these structural transformations.

The flatten attribute inlines a nested struct’s fields into the parent:

#[derive(Serialize, Deserialize)]
struct Pagination {
page: u32,
per_page: u32,
}
#[derive(Serialize, Deserialize)]
struct UserQuery {
search: String,
#[serde(flatten)]
pagination: Pagination,
}

This serializes as { "search": "...", "page": 1, "per_page": 20 } rather than nesting pagination inside its own object. Flattening works for composition patterns where logical grouping in code should not create structural grouping in the format. The technique also enables open-ended deserialization: a flattened HashMap<String, Value> captures unknown fields without discarding them, useful for forwarding or logging data that the current code does not directly consume.

Enum representation deserves careful consideration because the choice affects both wire format compatibility and human readability. The default external tagging wraps each variant in an object with the variant name as key, producing verbose output but maximizing explicitness. Different APIs and configuration formats have conventions that other representations better match. Internal tagging places the variant discriminator inside the content:

#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Message {
Request { id: u64, method: String },
Response { id: u64, result: String },
Error { id: u64, message: String },
}

This produces {"type": "Request", "id": 1, "method": "..." } rather than {"Request": { "id": 1, "method": "..." } }. Internal tagging requires variant content to be a struct or map since the tag must have somewhere to live.

Adjacent tagging places tag and content as siblings:

#[derive(Serialize, Deserialize)]
#[serde(tag = "event", content = "data")]
enum Event {
Click { x: i32, y: i32 },
KeyPress { key: char },
Resize { width: u32, height: u32 },
}

This produces {"event": "Click", "data": { "x": 10, "y": 20 } }. Adjacent tagging works with any variant content, including tuples and primitives.

Untagged representation omits the variant name entirely, relying on content structure for disambiguation:

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum Value {
Integer(i64),
Float(f64),
Text(String),
List(Vec<Value>),
}

Serde tries each variant in order during deserialization, using the first that successfully parses. Untagged enums require careful variant ordering since ambiguous inputs match the first compatible variant.

Working with JSON

JSON is the most common serialization format in web development. The serde_json crate provides a high-quality JSON implementation with strong performance and complete feature support. Understanding serde_json’s API patterns prepares you for other format crates, which follow similar conventions.

Serialization converts Rust values to JSON strings:

use serde_json;
let user = User {
id: 42,
username: "alice".to_string(),
email: "[email protected]".to_string(),
active: true,
};
let json = serde_json::to_string(&user)?;
// {"id":42,"username":"alice","email":"[email protected]","active":true}
let pretty = serde_json::to_string_pretty(&user)?;
// Formatted with indentation for readability

Deserialization parses JSON into Rust values:

let json = r#"{"id": 42, "username": "alice", "email": "[email protected]", "active": true}"#;
let user: User = serde_json::from_str(json)?;

The type annotation on the destination variable guides deserialization. Serde_json returns a Result, with errors indicating parse failures or type mismatches. Error messages include context about where parsing failed, aiding debugging of malformed input.

For working with JSON of unknown structure, serde_json provides the Value type:

use serde_json::Value;
let data: Value = serde_json::from_str(json_string)?;
if let Some(name) = data.get("name").and_then(Value::as_str) {
println!("Name: {}", name);
}

Value represents arbitrary JSON and supports indexing, iteration, and dynamic type checking. While less efficient than deserializing to concrete types, Value handles APIs with variable schemas or exploratory parsing. The trade-off between typed deserialization and Value mirrors the trade-off between static and dynamic typing more broadly: Value provides flexibility at the cost of compile-time guarantees and runtime efficiency.

In practice, a hybrid approach often works best. Deserialize known structure into typed structs while capturing unknown extensions into a HashMap<String, Value> or flattened Value field. This pattern handles evolving APIs where new fields appear without breaking existing code.

The json! macro constructs JSON values with literal syntax, providing an ergonomic way to build dynamic JSON structures:

use serde_json::json;
let payload = json!({
"name": "test",
"values": [1, 2, 3],
"nested": {
"flag": true
}
});

Variables interpolate into the macro, and the result is a serde_json::Value. This approach suits building dynamic JSON where the structure is not fixed at compile time.

Other formats: TOML, YAML, binary

Serde’s format-agnostic design means switching formats often requires only changing the serializer crate. Each format has characteristics that suit different use cases.

TOML (Tom’s Obvious Minimal Language) targets configuration files with its human-friendly syntax. The toml crate provides serde integration:

use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct ServerConfig {
host: String,
port: u16,
workers: usize,
}
let config: ServerConfig = toml::from_str(r#"
host = "localhost"
port = 8080
workers = 4
"#)?;

TOML’s table syntax maps naturally to nested structs. Array-of-tables syntax handles vectors of structs. The format’s simplicity limits expressiveness but reduces parsing ambiguity, making configuration files more predictable.

YAML offers more expressiveness than TOML, supporting complex structures, anchors for deduplication, and multi-document streams. The serde_yaml crate provides integration:

let config: Config = serde_yaml::from_str(yaml_string)?;
let yaml_output = serde_yaml::to_string(&config)?;

YAML’s flexibility comes with complexity. Indentation-sensitivity causes subtle bugs. Implicit typing (where yes becomes a boolean) surprises developers expecting strings. For configuration files, TOML’s constraints often prevent more problems than YAML’s flexibility solves.

Binary formats prioritize size and speed over human readability. Where text formats encode integers as digit sequences and require delimiters between values, binary formats use fixed-width or varint encodings that pack data densely. The performance difference can be substantial: binary serialization often runs five to ten times faster than JSON, with output sizes reduced by similar factors. For high-throughput systems where serialization overhead matters, binary formats transform what would be a bottleneck into a non-issue.

Bincode provides a compact binary format designed specifically for Rust:

let encoded: Vec<u8> = bincode::serialize(&data)?;
let decoded: DataType = bincode::deserialize(&encoded)?;

Bincode produces smaller output than text formats and serializes faster. The format is not self-describing (the deserializer must know the expected type), making it suitable for cases where both ends agree on the schema. Network protocols, caching layers, and inter-process communication often benefit from binary formats.

MessagePack offers a binary format with broader ecosystem support. Unlike bincode, MessagePack is cross-language and self-describing, trading some efficiency for interoperability:

use rmp_serde;
let bytes = rmp_serde::to_vec(&data)?;
let value: DataType = rmp_serde::from_slice(&bytes)?;

Choosing a format involves trade-offs. JSON offers universal support and debuggability. TOML suits configuration with its clean syntax. Binary formats provide performance when human readability is unnecessary. Serde’s abstraction allows deferring the choice or supporting multiple formats without changing type definitions.

Custom serialization logic

Derive macros handle common cases, but some types require custom serialization logic. Sensitive data might need masking. External types might lack serde support. Formats might require representations that differ from the Rust type’s structure.

The serialize_with and deserialize_with attributes specify custom functions for individual fields:

use serde::{Serialize, Deserialize, Serializer, Deserializer};
#[derive(Serialize, Deserialize)]
struct Credentials {
username: String,
#[serde(serialize_with = "mask_password")]
password: String,
}

[!missing-source] Printed pages 600–601 are absent from the scan (skipped between PDF 609 and PDF 610). The Credentials / mask_password custom-serialization example above is cut off, and the text resumes inside a later configuration example; the missing content cannot be reconstructed.

#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct ServerConfig {
pub host: String,
pub port: u16,
#[serde(default = "default_workers")]
pub workers: usize,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct DatabaseConfig {
pub url: String,
#[serde(default)]
pub pool_size: u32,
#[serde(default)]
pub timeout_seconds: u64,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct LoggingConfig {
pub level: String,
pub file: Option<PathBuf>,
}
fn default_workers() -> usize {
num_cpus::get()
}
impl Default for AppConfig {
fn default() -> Self {
Self {
server: ServerConfig::default(),
database: DatabaseConfig {
url: "postgres://localhost/app".to_string(),
pool_size: 10,
timeout_seconds: 30,
},
logging: LoggingConfig::default(),
}
}
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 8080,
workers: default_workers(),
}
}
}
impl Default for LoggingConfig {
fn default() -> Self {
Self {
level: "info".to_string(),
file: None,
}
}
}

Loading configuration combines file reading with deserialization, supporting multiple formats based on file extension:

use std::fs;
use std::path::Path;
pub fn load_config(path: &Path) -> Result<AppConfig, ConfigError> {
let content = fs::read_to_string(path)?;
let config = match path.extension().and_then(|e| e.to_str()) {
Some("toml") => toml::from_str(&content)?,
Some("yaml") | Some("yml") => serde_yaml::from_str(&content)?,
Some("json") => serde_json::from_str(&content)?,
_ => return Err(ConfigError::UnsupportedFormat),
};
Ok(config)
}

The configuration structs use #[serde(default)] at the container level, allowing partial configuration files where only non-default values need specification. Users can provide minimal configuration while the application fills in sensible defaults.

Environment variable overrides extend file-based configuration. The config crate combines file parsing with environment variables, command-line arguments, and other sources into a unified configuration layer. For simpler needs, manual environment variable handling after deserializing the base config works well:

impl AppConfig {
pub fn with_env_overrides(mut self) -> Self {
if let Ok(port) = std::env::var("APP_PORT") {
if let Ok(port) = port.parse() {
self.server.port = port;
}
}
if let Ok(url) = std::env::var("DATABASE_URL") {
self.database.url = url;
}
self
}
}

This pattern keeps configuration files as the primary source while allowing environment-specific overrides for deployment.

Serialization Essentials

Serde provides serialization and deserialization for Rust through compile-time code generation rather than runtime reflection. The architecture separates data structures from data formats, allowing any serializable type to work with any supported format.

Deriving Serialize and Deserialize covers most types. Attributes customize behavior: rename and rename_all handle naming conventions, skip and default control field participation, flatten inlines nested structures, and enum representation attributes (tag, content, untagged) control discriminator placement.

Format crates implement serde’s traits for specific formats. JSON through serde_json handles web APIs. TOML suits configuration files. Binary formats like bincode optimize for size and speed. The choice depends on use case requirements for human readability, cross language compatibility, and performance.

Custom serialization logic handles special cases through field-level attributes (serialize_with, deserialize_with) or full trait implementations. The serde_with crate provides helpers for common transformations.

Configuration file handling demonstrates practical serde usage: nested structs with defaults, optional fields, format detection, and environment variable overrides combine into robust configuration loading.

The next chapter surveys the Rust ecosystem, examining where to apply these foundations and how to continue developing Rust proficiency.