[SOLVED] [serde] one enum variant for multiple cases?

I'm about to deserialize some JSON, which looks like this:

{
    "Employees": [
        {
            "@xsi:type": "Teacher",
            "Age": 42
        },
        {
            "@xsi:type": "Doctor",
            "Age": 23
        }
    ]
}

and I want to deserialize it into a single Variant of an enum, like this:

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
#[serde(tag = "@xsi:type")]
enum Employee {
    #[serde(???)]
    Person {
        age: u8
    },
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
struct Root {
    pub employees: Vec<Employee>
}

Playground: Rust Playground

Is that possible to achieve? Otherwise I would have to specify dozens of enum variants which all would look alike... The only thing that get near of what I want is serde(alias) but what I really need is something like serde(one_of(Teacher, Doctor))

Thanks in advance!

Nevermind, #[serde(alias)] can be used multiple times and is exactly what I needed:

use serde_derive::{Deserialize, Serialize};

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
#[serde(tag = "@xsi:type")]
enum Employee {
    #[serde(alias = "Teacher")]
    #[serde(alias = "Doctor")]
    Person {
        age: u8
    },
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
struct Root {
    pub employees: Vec<Employee>
}

fn main() {
    let json = r#"{
        "Employees": [
            {
                "@xsi:type": "Teacher",
                "Age": 42
            },
            {
                "@xsi:type": "Doctor",
                "Age": 23
            }
        ]
    }"#;
    
    let root: Root = serde_json::from_str(json).unwrap();
    println!("{:?}", root);
}
3 Likes

This topic was automatically closed after 34 hours. New replies are no longer allowed.