Reputation: 7746
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.
Upvotes: 4
Views: 1956
Reputation: 2810
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 String
s in fields:
pub struct StringableMyStruct(MyStruct);
Upvotes: 4