Warm tip: This article is reproduced from stackoverflow.com, please click
json rust serde

How to implement a custom serialization only for serde_json?

发布于 2020-04-05 23:42:37

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.

Questioner
Vlad Frolov
Viewed
87
211k 2020-02-04 04:10

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);