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?
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}");
}
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())
}
}
Remember that Display
gives you a ToString
implementation for free.