Custom serialization

Serde's derive macro through #[derive(Serialize, Deserialize)] provides reasonable default serialization behavior for structs and enums and it can be customized to some extent using attributes. For unusual needs, Serde allows full customization of the serialization behavior by manually implementing Serialize and Deserialize traits for your type.

The traits each have a single method:

pub trait Serialize {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        S: Serializer;

pub trait Deserialize<'de>: Sized {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        D: Deserializer<'de>;

These methods are generic over the serialization format, represented by the Serializer and Deserializer traits. For example there is one Serializer type for JSON and a different one for Postcard.