How to Rename Fields During Serialization with Serde

Rename Serde struct fields during serialization using the #[serde(rename = "new_name")] attribute.

Use the #[serde(rename = "new_name")] attribute on the struct field to change its name in the serialized output. This tells Serde to map the internal Rust field to a different key in the JSON or other format.

use serde::Serialize;

#[derive(Serialize)]
struct User {
    #[serde(rename = "user_name")]
    username: String,
    #[serde(rename = "email_address")]
    email: String,
}

When serialized, username becomes user_name and email becomes email_address in the output.