Serde_json untagged enum

I'm trying to deserialize JSON structures like below while making the best possible use of enums:

{
            "id": "1",
            "schema": "Person",
            "properties": {
                "name": "John Doe"
            }
        }

but also

{
        "id": "4",
        "schema": "Company",
        "properties": {
            "employee_count": 42,
        }   
    }

Playground link

Is it at all possible to have something like this to deserialize into? Or do I need a custom deserializer?

#[derive(Debug, Deserialize)]
#[serde(tag = "schema", content = "properties")]
enum EntityType {
    Person {
        name: String,
    },
    Company {
        employee_count: usize,
    },
}

All you need that you're missing is #[serde(flatten)] to get id and schema into the same JSON object:

#[derive(Debug, Deserialize)]
#[serde(tag = "schema", content = "properties")]
enum EntityType {
    Person { name: String },
    Company { employee_count: u32 },
}

#[derive(Debug, Deserialize)]
struct Entity {
    id: String,

    #[serde(flatten)]
    properties: EntityType,
}
2 Likes

Thank you so much! :raising_hands: