Rust

Serde — Field Rename, Skip, and Tagging

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Per-field attributes let you map between Rust's snake_case and the JSON's camelCase, skip optional fields, and tag enum variants the way external APIs expect.
Rust
Raw
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]                  // all fields camelCase in JSON
struct ApiUser {
    user_id: u64,                                   // → "userId"
    display_name: String,                           // → "displayName"

    #[serde(skip_serializing_if = "Option::is_none")]
    avatar_url: Option<String>,                     // omitted from output if None

    #[serde(rename = "isAdmin", default)]
    admin: bool,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type", content = "data")]            // externally-tagged form
enum Event {
    UserSignedUp { user_id: u64 },
    OrderPlaced  { order_id: u64, total: f64 },
}

fn main() {
    let u = ApiUser { user_id: 1, display_name: "Alice".into(), avatar_url: None, admin: true };
    println!("{}", serde_json::to_string(&u).unwrap());
    // {"userId":1,"displayName":"Alice","isAdmin":true}

    let e = Event::OrderPlaced { order_id: 42, total: 99.95 };
    println!("{}", serde_json::to_string(&e).unwrap());
    // {"type":"OrderPlaced","data":{"order_id":42,"total":99.95}}
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.