Skip to content

Instantly share code, notes, and snippets.

@silmeth
Created May 16, 2019 18:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silmeth/62a92e155d72bb9c5f19c8cdf4c8993e to your computer and use it in GitHub Desktop.
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
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()
);
}
@silmeth
Copy link
Author

silmeth commented May 16, 2019

Based on the discussion at serde#661.

The output of this code is:

Foo { bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] }
{"bytes":"EA8ODQwLCgkIBwYFBAMCAQA="}

@saman3d
Copy link

saman3d commented Jan 12, 2024

what about Option<Vec>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment