dtolnay / request-for-implementation

Crates that don't exist, but should
610 stars 6 forks source link

Attribute macro to skip serializing all fields of Option type #18

Closed dtolnay closed 5 years ago

dtolnay commented 5 years ago

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>,
    /* ... */
}
jonasbb commented 5 years ago

I'm tackling this issue over at https://github.com/jonasbb/serde_with/pull/46

EDIT: This feature is included in version 1.3.0 of serde_with.

jonathan-s commented 5 years ago

Looks like this feature is completed, no?

Warfields commented 5 years ago

???

DrSensor commented 5 years ago

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 🤔