Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a custom serialization only for serde_json?

Tags:

json

rust

serde

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.

like image 310
Vlad Frolov Avatar asked Oct 26 '25 05:10

Vlad Frolov


1 Answers

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);
like image 194
MaxV Avatar answered Oct 28 '25 19:10

MaxV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!