We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie serde-guide

Serde Guide

[rust][serialization][json]
Rust
Install
cargo add serde --features derive
cargo add serde_json

Serde is the standard serialization framework for Rust. Compile-time derive macros generate ser/de impls.

Supports JSON, YAML, TOML, BSON, MessagePack, and 50+ other formats via data format crates.

The derive API means zero runtime reflection: serialization is as fast as hand-written code.

Setup

Add deps· Cargo.toml entries.
cargo add serde --features derive
cargo add serde_json

Derive Macros

Derive basics· Standard ser/de.
#[derive(Serialize, Deserialize, Debug)]
struct User {
    id: u64,
    name: String,
    email: String,
}
Rename fields· Change serialized names.
#[derive(Serialize, Deserialize)]
struct User {
    #[serde(rename = "user_id")]
    id: u64,
    #[serde(rename = "full_name")]
    name: String,
}
Skip field· Omit from serialization.
#[derive(Serialize)]
struct User {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    age: Option<u32>,
}
Default values· Defaults on deserialize.
#[derive(Deserialize, Default)]
struct Config {
    #[serde(default = "default_port")]
    port: u16,
    #[serde(default)]
    host: String,
}

JSON

Serialize to JSON· Struct to JSON string.
let user = User { id: 1, name: "Alice".into(), email: "a@b.com".into() };
let json = serde_json::to_string(&user)?;
println!("{json}");
Deserialize from JSON· JSON string to struct.
let json = r#"{"id":1,"name":"Alice","email":"a@b.com"}"#;
let user: User = serde_json::from_str(json)?;

Custom Serialization

Custom deserialize· Manual deserialization.
impl Visitor<'_> for ColorVisitor {
    type Value = Color;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "a hex color") }
    fn visit_str<E: de::Error>(&self, v: &str) -> Result<Color, E> {
        Color::from_hex(v).ok_or_else(|| de::Error::custom("invalid color"))
    }
}

Advanced

Flatten· Inline nested struct.
#[derive(Serialize)]
struct Response {
    status: String,
    #[serde(flatten)]
    data: User,
}  // {"status":"ok","id":1,"name":"Alice"}