Vlad Frolov
Vlad Frolov

Reputation: 7746

How to implement a custom serialization only for serde_json?

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

Answers (1)

MaxV
MaxV

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 Strings in fields:

pub struct StringableMyStruct(MyStruct);

Upvotes: 4

Related Questions