How can I support an unknown or other value for a Serde enum?

前端 未结 3 675
野的像风
野的像风 2021-01-14 01:09

I have a JSON API that returns an object that looks like this:

{
  \"PrivatePort\": 2222,
  \"PublicPort\": 3333,
  \"Type\": \"tcp\"
}

To

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-14 01:42

    I do it with serde(from="String")

    #[derive(Eq, PartialEq, Deserialize, Serialize, Debug)]
    #[serde(rename_all = "snake_case", from="String")]
    pub enum PortType {
        Sctp,
        Tcp,
        Udp,
        Unknown(String),
    }
    
    impl From for PortType {
        fn from(s: String)->Self {
            use PortType::*;
    
            return match s.as_str() {
                "sctp" => Sctp,
                "tcp" => Tcp,
                "udp" => Udp,
                _ => Unknown(s)
            }
        }
    }
    
    #[derive(Deserialize, Serialize, Debug)]
    #[serde(rename_all = "PascalCase")]
    pub struct PortMapping {
        pub private_port: u16,
        pub public_port: u16,
        #[serde(rename = "Type")]
        pub port_type: PortType,
    }
    

提交回复
热议问题