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

Tag enums differently for serialization and deserialization #2828

Open
zaghaghi opened this issue Sep 26, 2024 · 0 comments
Open

Tag enums differently for serialization and deserialization #2828

zaghaghi opened this issue Sep 26, 2024 · 0 comments

Comments

@zaghaghi
Copy link

It might be a rare usecase and I have workaround for it, but it would be nice if we could settag container attribute separatly for serialization and deserialization.

To simplify the request, here is a json i would like to deserialize into an enum:

{"struct_type":"A","data":10}

and here is the json that i would like to serialize with the same enum

{"structType":"A","data":10}

and here is my enum definition works only for deserialization:

#[derive(Deserialize, Serialize)]
pub struct A {
    pub data: u8,
}

#[derive(Deserialize)]
#[serde(tag = "struct_type")]
pub enum AB {
    A(A),
}

my workaround is to write a custom serializater, something like this:

impl Serialize for AB {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        #[derive(Serialize)]
        struct EnumTagged<T> {
            #[serde(rename = "structType")]
            struct_type: String,
            #[serde(flatten)]
            base: T,
        }

        match self {
            AB::A(field) => {
                let e = EnumTagged {
                    struct_type: "A".into(),
                    base: field,
                };
                e.serialize(serializer)
            }
        }
    }
}

My suggestion is to have a specific tag for each of serialization and deserialization.

#[derive(Serialize, Deserialize)]
#[serde(tag(serialize= "struct_type", deserialize="structType"))]
pub enum AB {
    A(A),
}
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

1 participant