I want to be able to serialize a Vec<u8> as a base64-encoded string for JSON (and other UTF-8-based formats) while keeping an array of bytes for binary serialization formats.
#[derive(Serialize, Deserialize)]
struct MyStruct {
binary_data: Vec<u8>,
}
By default, serde_json will serialize the binary_data field as an array of numbers. Instead, I want to have it serialized as a string encoded with base64. Yet, I want to keep bincode (or any other binary format) using raw bytes and avoid base64 conversion.
The only solution I came up with is to create a copy of a data structure specifically for the serializer, but that is really annoying and inefficient when you have nested structures.
Based on Derde's documentation, you can't provide a special implementation of the Serialize trait for a concrete serializer for the same structure.
You can create a newtype struct and then provide a custom serde::{Des,S}erialize implementation for StringableMyStruct to support Strings in fields:
pub struct StringableMyStruct(MyStruct);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With