How to serialize enums to string with Serde

Tags:
  • Rust
  • Serde

Published


This took me a few attempts to get right, so here's a note to self. In hindsight, the documentation is pretty clear, but there are no examples, so I overlooked it.

If you have a struct with an enum field and you want to serialize the enum to a string using Serde and deriving Serialize, you can use the rename_all or rename attribute macros.

rename_all

If your enum follows one of the conventions implemented in Serde, your best bet is to use the rename_all attribute macro to tell Serde to use a specific naming convention for serializing the enum variants.

#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
enum FlightLength {
    ShortHaul,
    MidHaul,
    LongHaul,
}

#[derive(Serialize)]
struct Flight {
    length: FlightLength,
}

let f = Flight {
    length: FlightLength::ShortHaul,
};

let j = serde_json::to_string(&address)?;
assert_eq!(j, r#"{"length":"short-haul"}"#);

Link to a playground that compiles and run.

This is applicable for: "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE".

rename

If your enum doesn't follow a convention, you can instead rename each variant.

#[derive(Serialize)]
enum FlightLength {
    #[serde(rename = "SHORT HAUL")]
    ShortHaul,
    #[serde(rename = "MID HAUL")]
    MidHaul,
    #[serde(rename = "LONG HAUL")]
    LongHaul,
}

#[derive(Serialize)]
struct Flight {
    length: FlightLength,
}

let f = Flight {
    length: FlightLength::ShortHaul,
};

let j = serde_json::to_string(&address)?;
assert_eq!(j, r#"{"length":"SHORT HAUL"}"#);

Link to a playground that compiles and run.