Home > Net >  Deserializing JSON field with possible choices using serde
Deserializing JSON field with possible choices using serde

Time:01-12

I'm trying to use serde json deserialization to support "choices" using enum, but it doesn't seep to be working (I have python enum background) let's say I have this json :

{"name": "content", "state": "open"}

and state can be open or closed

in python I would just create an enum and the state type would be that enum eg:

#[derive(Deserialize)]
enum State {
    Open(String),
    Closed(String),
}

#[derive(Deserialize)]
struct MyStruct {
    name: String,
    state: State,
}

and the problem is that I don't know how to derserialize open to State::Open and closed to State::Closed I have looked into implementing my own deserializer, but it seems very complicated and very advanced for me.

is there any straightforward way ?

CodePudding user response:

You should remove the String. Then you'll get another error:

unknown variant `open`, expected `Open` or `Closed`

Because your enum variants are in PascalCase while your JSON is in camelCase (or snake_case, I don't know). To fix that, add #[serde(rename_all = "camelCase")]:

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
enum State {
    Open,
    Closed,
}
  • Related