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

前端 未结 3 684
野的像风
野的像风 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:31

    There's an issue for this, though it's been open for 3 years with no full resolution so far. Serde #912.

    What seems to be currently implemented (though undocumented) at the time of this post is #[serde(other)]. It can only be applied to unit enum fields, which limits its usefulness:

    #[derive(Deserialize, PartialEq)]
    #[serde(tag = "tag")]
    enum Target {
       A(()),
       B(()),
       #[serde(other)]
       Others
    }
    
    fn main() {
        assert_eq!(Target::Others, from_str::(r#"{ "tag": "blablah" }"#).unwrap());
    }
    

    Other than that, the only other method as of this writing is writing your own Deserialize implementation.

提交回复
热议问题