Created
December 8, 2021 21:28
-
-
Save sbeckeriv/7317eb6e51189a784c02cb34900c6f95 to your computer and use it in GitHub Desktop.
change a rust struct to a single string and back in serde for serde_json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// currently MyId Serialize to a string | |
#[derive(Hash, PartialEq, Eq, Debug, Clone, Deserialize, Serialize)] | |
pub struct MyId(pub String); | |
// i want to change it so that i format my string so it is safe. In this case I want to | |
// base64 it. I create a ::new that does this. I want my json to stay the same and validate | |
// the json value is real base64. | |
#[derive(Hash, PartialEq, Eq, Debug, Clone, Deserialize)] | |
#[serde(try_from = "String")] | |
pub struct MyId { | |
raw_id: String, | |
} | |
impl TryFrom<String> for MyId { | |
type Error = String; | |
fn try_from(id: String) -> Result<Self, Self::Error> { | |
match base64::decode_config(&id, base64::URL_SAFE) { | |
Ok(_) => Ok(MyId { raw_id: id }), | |
_ => Err(format!("can not covert string from base64 {}", id)), | |
} | |
} | |
} | |
impl Serialize for MyId { | |
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> | |
where | |
S: Serializer, | |
{ | |
serializer.serialize_str(&self.raw_id) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment