Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip serde serialization with skip_serializing_if for a boolean field

Tags:

rust

serde

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,
}
like image 445
Yuri Astrakhan Avatar asked Jan 26 '26 23:01

Yuri Astrakhan


2 Answers

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, or <&bool>::not for short.
like image 184
Caesar Avatar answered Jan 29 '26 04:01

Caesar


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,
}
like image 30
cdbfoster Avatar answered Jan 29 '26 02:01

cdbfoster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!