I would like to skip field serialization if the value is false
.
In JSON, this would serialize Foo
as either {bar: true}
or {}
.
#[derive(Serialize)]
pub struct Foo {
// This does not compile - bool::is_false does not exist
#[serde(skip_serializing_if = "bool::is_false")]
pub bar: bool,
}
Well, according to the serde docs:
#[serde(skip_serializing_if = "path")]
Call a function to determine whether to skip serializing this field. The given function must be callable asfn(&T) -> bool
, although it may be generic overT
So you can either define such a function yourself
fn is_false(b: &bool) -> bool { !b }
Or you could look for such a function in the standard library.
Clone::clone
std::ops::Not::not
(Playground)bool::not
won't work because you need the Not
impl on
&bool
: <&bool as std::ops::Not>::not
, or <&bool>::not
for short.