serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
8.82k stars 748 forks source link

Double quotes included when serializing an enum to a string #2696

Closed R2-t closed 4 months ago

R2-t commented 4 months ago

I have the following enum:

#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Statuses {
    Available,
    Failed,
    NotFound,
    Processing,
    NotAvailable,
}

And whenever I try to serialize it, I get it back with double quotes around the value, which means that if I run this test I will fail.

#[cfg(test)]
mod test {
    #[test]
    fn serialize_statuses() {
        use serde_json::to_string;
        use super::Statuses;

        let expected_value = String::from("AVAILABLE").trim_matches();
        let serialized_value = to_string(&CollectionStatuses::Available).unwrap();

        assert_eq!(expected_value, serialized_value)
    }
}

I don't think it should be the expected result from it, but if I can get some clarification or help it'd be great!

oli-obk commented 4 months ago

Here's a playground repro: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cfe82dae43a6307d44955e72f551871a

This behaviour is correct. When you use assert_eq, the string will be printed with debug printing, so you'll see quotes around the string. The string is supposed to contain quotes, as that's how json represents strings.

If you want to see how the string looks really, you should print it with println!("{expected_value} == {serialized_value}");

You need to change your expected value to be r##""AVAILABLE""##