2021年3月21日星期日

How can I deserialize a fieldless enum from either a string or number?

Is there a succinct way to deserialize a variant of a fieldless enum from either its name or discriminant value? e.g. given this enum—

enum Foo {      A = 1,      B = 2,      C = 3,  }  

—I'd like any of these strings or numbers to represent it:

{    "example-a": "a", // Foo::A    "example-b": "b", // Foo::B    "example-c": "c", // Foo::C      "example-1": 1, // Foo::A    "example-2": 2, // Foo::B    "example-3": 3, // Foo::C  }  

I've seen that deriving Deserialize accommodates the former group and Deserialize_repr the latter, but I'm not sure how to accommodate both simultaneously.

I expected that a shorthand like #[serde(alias = …)] might exist to cover this scenario.

https://stackoverflow.com/questions/66735996/how-can-i-deserialize-a-fieldless-enum-from-either-a-string-or-number March 22, 2021 at 02:23AM

没有评论:

发表评论