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: "[email protected]".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":"[email protected]"}"#;
let decoded: UserProfile = serde_json::from_str(payload)?;
println!("decoded: {decoded:?}");
assert_eq!(decoded.user_id, 9);
Ok(())
}
Report a problem with this exampleOpens a pre-filled issue on GitHub.