I'm trying to get the name of an enum variant as the string serde would expect/create. For example, say I have the following enum:
#[derive(Serialize, Deserialize)]
#[serde(rename_all="camelCase")]
pub enum SomeEnum {
WithoutValue,
withValue(i32),
}
How can I then get the serde names of the variants? Something like
serde::key_name(SomeEnum::WithoutValue) // should be `withoutValue`
serde::key_name(SomeEnum::WithValue) // should be `withValue`
I can use a hack with serde_json
, for variants without a value I can do:
serde_json::to_string(SomeEnum::WithoutValue).unwrap(); // yields `"withoutValue"` with quotation marks
This is not the best solution as I then need to strip the quotation marks, but can technically work.
Even worse is when the enum variant has a value. It becomes much messier.
serde_json::to_string(SomeEnum::WithValue(0)).unwrap(); // yields `"{\"second\":0}"
Is there a clean way to achieve this? I can't find a serde API to get key name as a string.
#[derive(Serialize, Deserialize)]
. What use do you have for this? Maybe there's another way of approaching the problem. – Oilbird