#[derive(SerializeDisplayAlt)]
{
// Attributes available to this derive:
#[serde_with]
}
Expand description
Serialize value by using its Display
implementation with the “alternate” (#
) format flag
This derive implements serde::Serialize
for any type that already implements
std::fmt::Display
, emitting its string form using the alternate formatting specifier
({:#}
) instead of the normal {}
. In other words, rather than calling
format!("{}", self)
, it calls format!("{:#}", self)
.
Ensure that your type implements Display
, or you will get a compile‐error such as:
error[E0277]: `MyType` doesn't implement `std::fmt::Display`
Deserialization from strings via std::str::FromStr
is handled by the companion
DeserializeFromStr
derive.
§Attributes
You may customize which serde_with
crate is used (for renamed or re-exported crates)
via the same attribute namespace:
#[serde_with(crate = "...")]
When your workspace renames or re-exportsserde_with
, use this to point at the correct path. For example:ⓘ#[derive(SerializeDisplayAlt)] #[serde_with(crate = "my_forked_serde_with")] pub struct Foo(/* … */);
§Example
ⓘ
use std::fmt;
use serde_with::{SerializeDisplayAlt, DeserializeFromStr};
#[derive(Debug, Clone, SerializeDisplayAlt, DeserializeFromStr)]
#[serde(transparent)]
pub struct MyType(u32);
impl fmt::Display for MyType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
// Alternate formatting: hex with 0x prefix
write!(f, "0x{:X}", self.0)
} else {
// Standard formatting: decimal
write!(f, "{}", self.0)
}
}
}
let v = MyType(15);
// SerializeDisplayAlt always uses `{:#}`, so this yields `"0xF"`
assert_eq!(r#""0xF""#, serde_json::to_string(&v).unwrap());