Created
May 16, 2019 18:49
-
-
Save silmeth/62a92e155d72bb9c5f19c8cdf4c8993e to your computer and use it in GitHub Desktop.
Serialization and deserialization byte array (Vec<u8>) to/from json in Rust as Base64 string using Serde
This file contains hidden or 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
use serde::{Deserialize, Deserializer, Serialize, Serializer}; | |
#[derive(Serialize, Deserialize, Debug)] | |
pub struct Foo { | |
#[serde(serialize_with = "as_base64", deserialize_with = "from_base64")] | |
bytes: Vec<u8>, | |
} | |
fn as_base64<T: AsRef<[u8]>, S: Serializer>(val: &T, serializer: S) -> Result<S::Ok, S::Error> { | |
serializer.serialize_str(&base64::encode(val)) | |
} | |
fn from_base64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> { | |
use serde::de; | |
<&str>::deserialize(deserializer).and_then(|s| { | |
base64::decode(s) | |
.map_err(|e| de::Error::custom(format!("invalid base64 string: {}, {}", s, e))) | |
}) | |
} | |
fn main() { | |
println!( | |
"{:?}", | |
serde_json::from_str::<Foo>(r#"{"bytes":"AQIDBAUGBwgJCgsMDQ4PEA=="}"#).unwrap() | |
); | |
println!( | |
"{}", | |
serde_json::to_string(&Foo { | |
bytes: vec![16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] | |
}) | |
.unwrap() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on the discussion at serde#661.
The output of this code is: