Recipe
Serde (Rust) primer
Serde is the de-facto serialization framework for Rust. It turns native structs and enums into JSON, YAML, MessagePack, or any other format with two derive macros and zero runtime reflection. This primer walks through the three patterns you will use 90% of the time when wiring Meridian payloads.
1. Derive Serialize and Deserialize
Add serde = { version = "1", features = ["derive"] } to Cargo.toml, then annotate your struct. Field names are preserved verbatim unless you rename them.
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Payload {
id: u64,
name: String,
tags: Vec<String>,
}2. Rename and skip fields
Rust uses snake_case but most JSON APIs use camelCase. The rename_all attribute handles the whole struct at once. Use skip_serializing_if to drop None or empty values from the wire format.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ApiResponse {
request_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
error_message: Option<String>,
}3. Tagged enums for sum types
When a payload can be one of several shapes, Serde supports internally-tagged, externally-tagged, and adjacently-tagged enums. The tag attribute encodes the variant name into a discriminator field which mirrors how most TypeScript discriminated unions read on the wire.
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum Event {
Connect { session_id: String },
Message { body: String },
Disconnect,
}