Serde skip field serialization depending on a "global" runtime condition

Viewed 490

Depending on some runtime condition, I'd like to either serialize a field or not. That condition applies to the whole serialization and has nothing to do with the field's value itself. Hence, I cannot use skip_serializing_if() if I understand it right, unless I use some sort of a global state, but then that would be more like a constant, not a "condition".

As an example, let's say the condition depends on the client that requested the file. Some clients will need to have that field, others - not.

If the condition says serialize, do so even if the field's value is None (i.e. explicitly create a property with null value in the output JSON).

What's the simplest and cleanest way to achieve that?

1 Answers

Just create a function and ignore the argument:

use serde_json; // 1.0.67
use serde::Serialize; // 1.0.130

fn condition_met<T>(_: &T) -> bool {
    false
}

#[derive(Serialize)]
struct Foo {
    #[serde(skip_serializing_if = "condition_met")]
    data: Option<u32>,
}

fn main() {
    println!("{}", serde_json::to_string(&Foo{data: None}).unwrap());
}

Playground

Related