#Issue with Serde's deserialization of an untagged enum

14 messages · Page 1 of 1 (latest)

unreal kayak
#

Hello, I'm looking for help regarding serde.

I'm trying to deserialize (and serialize) the following data that I get from a webhook call into my server:

{
    // ... other fields
    "customFields": {
        "case-type": {
            "string": "Alerte",
            "order": 0
        },
        "client": {
            "string": "FOO",
            "order": 1
        },
        "some-integer": {
            "integer": 123456789,
            "order": 2
        },
        "detection-date": {
            "date": 1704276420000,
            "order": 3
        },
    }
}

The way I want to deserialize it is as the following struct:

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged, rename = "camelCase")]
enum CustomField {
    Date {
        date: Option<u64>,
        order: usize,
    },
    Integer {
        integer: Option<u64>,
        order: usize,
    },
    String {
        string: Option<String>,
        order: usize,
    },
}

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Case {
    // .. other fields
    custom_fields: HashMap<String, CustomField>,
}

The problem I'm facing right now, is that serde seems to only pick the first variant of the CustomField an use it for everything, ignore the shape of variant.

is there a way I can do this? 🤔
and if not, how would I go about creating a custom Deserializer for this, if that is even practical?

Here's a link to a playground for demonstration:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ff73d0ed12eddbb1e183ab757c712e1e

final musk
unreal kayak
#

I sadly can't, since the request is coming from a different software. I don't have control over what it sends me

unreal kayak
#

The fields can be null

#

So, I can't remove the Option<T>

final musk
#

So the fields can be null, but they won't ever be missing?

#

So you could get something like

{
    "string": null,
    "order": 1
}```
but you won't get
```json
{
    "order": 1
}```
unreal kayak
#

Yes

#

I don't mind getting rid of the order field

#

It's not useful to me

final musk
#

See if possibly the serde(deny_unknown_fields) attribute on the enum works for this

unreal kayak
#

Ok, I'll try that as soon as possible

(I'd try it now, but I'm a bit sick and just wanna go rest)

#

Thank you in advance