jsonrustserde

How to serde deserialize enum variant from string with dashes?


I need to deserialize some existing JSON data using serde. One of the fields should be an enum but one of the possible values in the JSON includes a "-" character. Like this:

{
    "fubar": "foo-bar"
}

Insofar as I have been able to determine, enum variants can't have dashes in their names.

How do I deserialize data that might contain dashes? I tried looking through the serde documentation but haven't been able to find anything.


Solution

  • Use #[serde(rename)]:

    enum Foo {
        #[serde(rename = "foo-bar")]
        FooBar,
    }