Skip to content
This repository was archived by the owner on Jul 9, 2023. It is now read-only.
This repository was archived by the owner on Jul 9, 2023. It is now read-only.

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

@dtolnay

Description

@dtolnay

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>,
    /* ... */
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions