Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combine "transparent" and "skip_serializing_if" tags #1870

Closed
dspicher opened this issue Aug 7, 2020 · 6 comments
Closed

Combine "transparent" and "skip_serializing_if" tags #1870

dspicher opened this issue Aug 7, 2020 · 6 comments

Comments

@dspicher
Copy link

dspicher commented Aug 7, 2020

I would like to have a transparent struct with a single field, whose serialization is skipped if some condition is fulfilled:

#[derive(serde::Serialize)]
#[serde(transparent)]
struct Foo {
    #[serde(skip_serializing_if = "String::is_empty")]
    inner: String,
}

However, if the transparent tag is included, the inner tag is ignored, i.e. this compiles:

#[derive(serde::Serialize)]
#[serde(transparent)]
struct Foo {
    #[serde(skip_serializing_if = "String::i_am_ignored")]
    inner: String,
}

Is this expected behaviour?

@dtolnay
Copy link
Member

dtolnay commented Aug 7, 2020

What would you want the serialized representation to be if skipped?

@dtolnay
Copy link
Member

dtolnay commented Aug 7, 2020

By which I mean, in the case of something like:

use serde::Serialize;

#[derive(Serialize)]
#[serde(transparent)]
struct Foo {
    #[serde(skip_serializing_if = "String::is_empty")]
    inner: String,
}

fn main() {
    let empty_foo = Foo { inner: String::new() };
    println!("{}", serde_json::to_string(&empty_foo).unwrap());
}

@dspicher
Copy link
Author

Well, is there something like an empty serialization?

@dspicher
Copy link
Author

To clarify the intent, I would like to use this on an optional field, not on the top-level serialization object.

@toxeus
Copy link

toxeus commented Sep 23, 2020

Related: #65 (comment)

@dtolnay
Copy link
Member

dtolnay commented Jul 9, 2023

There isn't something like an empty serialization. When a Serialize impl runs, the only way it can succeed is by serializing something.

The thing whose field this is can decide not to serialize that field, though.

@dtolnay dtolnay closed this as completed Jul 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants