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

#1

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: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a9117631a15ddc1d57eb51466bbce4a1

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!

#2

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
closed #3

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