Rust - Enum serialization example

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use serde::ser::{ Serialize, Serializer };
use serde::de::{ Deserialize, Deserializer };
pub enum EnumTestType {
    Type1,
    Type2,
    UNKNOWN,
}
impl EnumTestType {
    pub fn value(&self) -> &'static str {
        match *self {
            EnumTestType::Type1 => "T1",
            EnumTestType::Type2 => "T2",
            EnumTestType::UNKNOWN => "?",
        }
    }
}
impl Serialize for EnumTestType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer,
    {
        serializer.serialize_str(self.value())
    }
}
impl <'a> Deserialize<'a> for EnumTestType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'a>,
    {
        let s = String::deserialize(deserializer)?;
        let result = match s.as_str() {
            "D" => EnumTestType::Type1,
            "I" => EnumTestType::Type2,
            _ => EnumTestType::UNKNOWN,
        };
        Ok(result)
    }
}