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

How to define integer tag in enum? #2252

Open
lz1998 opened this issue Aug 4, 2022 · 3 comments
Open

How to define integer tag in enum? #2252

lz1998 opened this issue Aug 4, 2022 · 3 comments

Comments

@lz1998
Copy link

lz1998 commented Aug 4, 2022

https://serde.rs/enum-representations.html#adjacently-tagged

{"t": "Str", "c": "the string"}{"t": 1, "c": "the string"}
{"t": "Para", "c": [{...}, {...}]}{"t": 2, "c": [{...}, {...}]}

#[derive(Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum Block {
    Para(Vec<Inline>),
    Str(String),
}
@edgarogh
Copy link

edgarogh commented Aug 30, 2022

Serde's enum variant serializers rely on strings1 and there's no way around that without modifying serde_json2 in your case. You will probably have to implement the (de)serialization of Block yourself if you really need this feature.

For instance, for Serialize :

impl Serialize for Block {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer
    {
        #[derive(Serialize)]
        #[serde(rename = "Block")]
        struct AdjTagged<T> {
            t: u8,
            c: T,
        }

        match self {
            Block::Para(field) => AdjTagged { t: 1, c: field }.serialize(serializer),
            Block::Str(field) => AdjTagged { t: 2, c: field }.serialize(serializer),
        }
    }
}

Footnotes

  1. https://docs.rs/serde/latest/serde/trait.Serializer.html#tymethod.serialize_tuple_variant

  2. https://docs.rs/serde_json/1.0.85/src/serde_json/ser.rs.html#358-383

@kangalio
Copy link

Duplicate of #745

@Mingun
Copy link
Contributor

Mingun commented Aug 11, 2023

While this is essentially a duplicate of #745, the latest changes from #2505 probably could solve the original problem

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

4 participants