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::clonestd::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.The simplest answer is to use the output of the Not::not function, which is already implemented for &bool.
use std::ops::Not;
#[derive(Serialize)]
pub struct Foo {
#[serde(skip_serializing_if = "<&bool>::not")]
pub bar: bool,
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With