[英]How do I configure Serde to use an enum variant's discriminant rather than name?
I'm parsing an INI-style file that uses integers for enumerators.我正在解析一个使用整数作为枚举器的 INI 样式文件。
#[derive(Debug, Deserialize, Serialize)]
pub enum MyThing {
First = 0,
Second = 1,
Third = 2,
}
In the file, the value will get serialized like so:在文件中,值将像这样被序列化:
thing=0
However, Serde by default matches against the variant name rather than the discriminant.但是,默认情况下,Serde 匹配变体名称而不是判别式。 Is custom-implementing
Deserialize
the cleanest method?自定义实现
Deserialize
是最干净的方法吗?
The Serde website has an entire example on how to serialize an enum as a number : Serde 网站有一个关于如何将枚举序列化为数字的完整示例:
[dependencies] serde = "1.0" serde_repr = "0.1"
use serde_repr::*; #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] #[repr(u8)] enum SmallPrime { Two = 2, Three = 3, Five = 5, Seven = 7, } fn main() { use SmallPrime::*; let nums = vec![Two, Three, Five, Seven]; // Prints [2,3,5,7] println!("{}", serde_json::to_string(&nums).unwrap()); assert_eq!(Two, serde_json::from_str("2").unwrap()); }
I would believe that this is the best way to do it as it's recommended by the crate authors themselves.我相信这是最好的方法,因为它是由板条箱作者自己推荐的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.