rustserde

How to get renamed enum name from enum value?


So I have

#[derive(Deserialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}

I want to get from let i = ComparisonOperators::GE to ">=". Can I do this by not adding a mapper?


Solution

  • You can add the Serialize tag, and then use the serde_json to serialize to a String as per your attributes renaming:

    use serde::{Deserialize, Serialize};
    use serde_json; // 1.0.78
    
    #[derive(Deserialize, Serialize, Clone, Debug, Copy)]
    pub enum ComparisonOperators {
        #[serde(rename = "=")]
        EQ,
        #[serde(rename = "!=")]
        NEQ,
        #[serde(rename = ">")]
        GT,
        #[serde(rename = ">=")]
        GE,
        #[serde(rename = "<")]
        LT,
        #[serde(rename = "<=")]
        LE,
    }
    
    fn main() {
        let tag = serde_json::to_string(&ComparisonOperators::EQ).unwrap();
        println!("{tag}");
    }
    

    Playground

    You can even implement display for your enum based on that:

    impl fmt::Display for ComparisonOperators {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", serde_json::to_string(self).unwrap())
        }
    }
    

    Playground

    Remember that Display gives you a ToString implementation for free.