[Serde-YAML] Deserialization a Enum

Hello.
I have the enum Slots and the struct Bus:

#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum Slots {
    DYNAMIC(String),
    ENUMERATION(Vec<String>),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Bus {
    id: String,
    slots: Slots,    
}

and two YAML strings:

let enum_yaml = r#"id: bus-0.0.1
slots: [1,2,3,4,5,6,7,8]"#;

let dynamic_yaml = r#"id: bus-0.0.1
slots: dynamic"#;

How to deserialize it?
For a JSON file, we have tags.
https://serde.rs/enum-representations.html#adjacently-tagged

Full Example: Playground

You need to use an untagged enum:

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
enum Slots {
    DYNAMIC(String),
    ENUMERATION(Vec<u32>),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Bus {
    id: String,
    slots: Slots,    
}
1 Like

@moises-marquez thanks for your reply.
If I have that:

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
enum Slots {
    Dynamic,
    Other,
    EnumerationU32(Vec<u32>),
    EnumerationString(Vec<String>),
}

what in this case?

Playground

I think that the simplest approach would be to separate your string slots into another enum:

#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
enum Slots {
    SlotString(SlotString),
    EnumerationU32(Vec<u32>),
    EnumerationString(Vec<String>),
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
enum SlotString {
    #[serde(rename = "dynamic")]
    Dynamic,
    #[serde(rename = "other")]
    Other
}

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Bus {
    id: String,
    slots: Slots,    
}

Thanks.
Playground

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.