Derive Macro serde_with::SerializeDisplay

source ·
#[derive(SerializeDisplay)]
{
    // Attributes available to this derive:
    #[serde_with]
}
Available on crate feature macros only.
Expand description

Serialize value by using it’s Display implementation

This is an alternative way to implement Serialize for types, which also implement Display by serializing the type as string. Ensure that the struct/enum also implements Display. If the implementation is missing, you will get an error message like

error[E0277]: `Struct` doesn't implement `std::fmt::Display`

Deserialization with FromStr is available with the matching DeserializeFromStr derive.

Attributes

Attributes for the derive can be specified via the #[serde_with(...)] attribute on the struct or enum. Currently, these arguments to the attribute are possible:

Example

use std::fmt;

#[derive(SerializeDisplay)]
struct A {
    a: u32,
    b: bool,
}

impl fmt::Display for A {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}<>{}", self.a, self.b)
    }
}

let a = A { a: 123, b: false };
assert_eq!(r#""123<>false""#, serde_json::to_string(&a).unwrap());