Derive Macro serde_with_macros::SerializeDisplay
source · [−]#[derive(SerializeDisplay)]
{
// Attributes available to this derive:
#[serde_with]
}
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:
-
#[serde_with(crate = "...")]
: This allows usingSerializeDisplay
whenserde_with
is not available from the crate root. This happens while renaming dependencies in Cargo.toml or when re-exporting the macro from a different crate.This argument is analogue to serde’s crate argument and the crate argument to
serde_as
.
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());