Last active
May 16, 2025 17:17
-
-
Save cmackenzie1/7f61fb1bf3256620f74d9259898127e8 to your computer and use it in GitHub Desktop.
Encode and Decode Base64 fields in JSON using Rust
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
[dependencies] | |
serde = { version = "1", features = ["derive"] } | |
serde_json = "1" | |
base64 = "0.22" |
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
mod base64 { | |
use base64::prelude::*; | |
use serde::{Deserialize, Serialize}; | |
use serde::{Deserializer, Serializer}; | |
pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> { | |
let base64 = BASE64_STANDARD.encode(v); | |
String::serialize(&base64, s) | |
} | |
pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> { | |
let base64 = String::deserialize(d)?; | |
BASE64_STANDARD | |
.decode(base64.as_bytes()) | |
.map_err(serde::de::Error::custom) | |
} | |
} | |
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] | |
pub struct Message { | |
#[serde(with = "base64")] | |
pub payload: Vec<u8>, | |
} | |
fn main() { | |
let a = Message { payload: b"hello world".into() }; | |
println!("{:?}", a); | |
let a_json = serde_json::to_string(&a).unwrap(); | |
println!("{}", a_json); | |
let b: Message = serde_json::from_str(&a_json).unwrap(); | |
println!("{:?}", b); | |
assert_eq!(a.payload, b.payload); | |
} |
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
Message { payload: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] } | |
{"payload":"aGVsbG8gd29ybGQ="} | |
Message { payload: [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment