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.
Code
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 ownmatch.
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.