How to Use #[serde(with)] for Custom Field Formats

Apply #[serde(with = "module")] to a field to use custom serialization and deserialization functions defined in that module.

Use #[serde(with = "module_path")] on a struct field to delegate serialization and deserialization to custom functions in that module.

use serde::{Serialize, Deserialize};

mod my_format {
    use serde::{Serializer, Deserializer};
    use serde::de::Error;

    pub fn serialize<S>(value: &String, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&value.to_uppercase())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<String, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(s.to_lowercase())
    }
}

#[derive(Serialize, Deserialize)]
struct Config {
    #[serde(with = "my_format")]
    name: String,
}