Serde: Deriving, JSON & Field Attributes
Serde ("SERialize/DEserialize") is the de facto standard Rust framework for converting Rust data structures to and from formats like JSON, YAML, and more. Its generic core plus separate format crates (serde_json, serde_yaml, bincode) let one derived struct serialize to many formats.
Deriving Serialize/Deserialize
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct User {
name: String,
age: u32,
}
let json = serde_json::to_string(&user)?;
let user: User = serde_json::from_str(&json)?;
// The derive macro generates the conversion code at compile time --
// no runtime reflection needed, unlike some other languages' serializersStrict Typing Catches Bad Data Early
A type mismatch or missing required field produces an explicit Result::Err at the parsing boundary -- not a subtle downstream bug from silently misinterpreted data.
Field Attributes
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
user_name: String, // -> "userName" in JSON
#[serde(default)]
bio: String, // falls back to Default if missing
#[serde(skip_serializing_if = "Option::is_none")]
avatar_url: Option<String>, // omitted from output entirely if None
}Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free