Search code examples
rustserde

How to skip serde serialization with skip_serializing_if for a boolean field


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,
}

Solution

  • 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 as fn(&T) -> bool, although it may be generic over T

    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.

    • For skipping true: Clone::clone
    • For skipping false: std::ops::Not::not (Playground)
      Note that bool::not won't work because you need the Not impl on &bool: <&bool as std::ops::Not>::not