Leonardo Raele
Leonardo Raele

Reputation: 2823

How do I customize the serialization and deserialization of structured data using serde_json?

I want to customize the JSON representation of my struct.

For example, given a Color struct...

pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

...with methods to convert to and from hexadecimal...

impl Color {
    pub fn from_hex(hex: &str) -> Self {
        // ...
    }

    pub fn to_hex(&self) -> String {
        // ...
    }
}

...I want Color to be serialized to and from a string, using those hexadecimal methods.

struct ColoredObject {
    color: Color,
}

assert_eq!(
    serde_json::to_string(
        ColoredObject {
            color: Color { r: 255, g: 0, b: 0, a: 0 },
        }
    ),
    "{\"color\":\"#FF000000\"}"
);

By default, serde_json would serialize it to {"color":{"r":255,"g":0,"b":0,"a":0}}.

Upvotes: 0

Views: 26

Answers (0)

Related Questions