rustwebassemblywasm-bindgen

Serialize a variable format field, one of two potential types


I am making a api request where one field can have to potential structures:

  • a string (example: "key": "24789223")
  • an object (example: "key": { value: "12121", "currency": "USD" })

I have tried to use an enum like this:

pub enum CustomAmount {
    ComplexAmount(ComplexAmount),
    SimpleAmount(String)
}

Where ComplexAmount is:

pub struct ComplexAmount {
    pub value: String,
    pub currency: String
}

However, when I try to deserialize from the json response I get the following error:

unknown variant `24789223 `, expected `CustomAmount` or `SimpleAmount`

I am using wasm-bindgen.

Is there a better way to allow a field to have two potential types?

Thanks


Solution

  • To be able to distinguish between two enum values (where there's not any extra info in the json like "__type": "ComplexAmount"), you need to add the #[serde(untagged)] macro to the enum declaration.

    #[derive(Debug, Deserialize)]
    #[serde(untagged)]
    pub enum CustomAmount {
        ComplexAmount(ComplexAmount),
        SimpleAmount(String)
    }
    

    also make sure you've used #[derive(Deserialize)] on ComplexAmount as well.