Serde Renaming for External JSON Fields

Map Rust field names to camelCase and reserved API keys with serde attributes while keeping a strongly typed struct.

RustData Integrity

Code

rustsnippet
31 lines
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
struct UserProfile {
    user_id: u64,
    display_name: String,
    #[serde(rename = "e-mail")]
    email: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    avatar_url: Option<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let profile = UserProfile {
        user_id: 7,
        display_name: "Ada Lovelace".to_string(),
        email: "ada@example.com".to_string(),
        avatar_url: None,
    };
    let encoded = serde_json::to_string(&profile)?;
    println!("encoded: {encoded}");
    assert!(!encoded.contains("avatarUrl"));

    let payload = r#"{"userId":9,"displayName":"Grace Hopper","e-mail":"grace@example.com"}"#;
    let decoded: UserProfile = serde_json::from_str(payload)?;
    println!("decoded: {decoded:?}");
    assert_eq!(decoded.user_id, 9);
    Ok(())
}

How it works

Serde Renaming for External JSON Fields reduces to the function main.

Fallible operations return Result, and the ? operator short-circuits errors up to the caller.

What to watch for

  • serde:: must be installed first — the snippet imports it directly.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

The entry-point signature is fn main() -> Result<(), Box<dyn std::error::Error>>

The demo output is labeled (encoded:, decoded:); each label names the call that printed it.

Statements that matter

let decoded: UserProfile = serde_json::from_str(payload)?;
let encoded = serde_json::to_string(&profile)?;

Interactive Tools for This Topic

FAQ

What is the error handling style?
Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does this need from the package registry?
These are real dependencies: `serde::`. Without it the snippet will not load.