How to parse a string to case which doesn't match the type in 3rd party crate?

Viewed 54

So this is some code from a 3rd party library:

#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Copy, Ord, PartialOrd)]
pub enum ViewingMetric {
    RatingPercentage,
    Rating
}

and what I would like is to parse a string like "rating_percentage" without being able to add #[serde(rename_all = "...")] into 3rd party code. Can I somehow specify the renaming during invocation of serde_json::from_str? Or must I add another 3rd party library which handles conversions between casings?

1 Answers

There is a guide on how to derive Serde for remote creates, in where you can customize whatever you need:

Would be something like:

#[derive(Serialize, Deserialize)]
#[serde(remote = "OtherCrate::ViewingMetric", rename_all = "snake_case")]
enum ViwingMetricSerde {
    RatingPercentage,
    Rating
}

Important, you would have to implement From/Into from your new type to the remote one From<ViwingMetricSerde> for ViwingMetric.

Then from your code, to actually get the original type:

#[derive(Serialize, Deserialize)]
pub struct MyStruct {
    #[serde(with = "ViwingMetricSerde")]
    metric: ViwingMetris
}
Related