Attribute macro to skip serializing all fields of Option type
dtolnay opened this issue · 4 comments
Some JSON workflows involve practically every piece of data being nullable and none of then being serialized when null. The Serde attributes in this situation can be verbose and distracting.
#[derive(Serialize)]
struct Data {
id: u64,
#[serde(skip_serializing_if = "Option::is_none")]
a: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
b: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
c: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
d: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
e: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
f: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
g: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
h: Option<String>,
}
It would be better to have an attribute macro that finds all fields of type Option<_> and inserts a skip_serializing_if attribute.
#[skip_serializing_null]
#[derive(Serialize)]
struct Data {
id: u64,
a: Option<String>,
b: Option<String>,
c: Option<String>,
d: Option<String>,
e: Option<String>,
f: Option<String>,
g: Option<String>,
h: Option<String>,
}
Optionally consider supporting an attribute to annotate optional fields that always need to be serialized, even when null.
#[skip_serializing_null]
#[derive(Serialize)]
struct Data {
id: u64,
#[always]
a: Option<String>,
b: Option<String>,
/* ... */
}
I'm tackling this issue over at jonasbb/serde_with#46
EDIT: This feature is included in version 1.3.0 of serde_with
.
Looks like this feature is completed, no?
???
I think this already shipped in the current crate serde_with
. I've used it and it works as expected. The only thing missing is the documentation 🤔