如何支持Serde枚举类型中的未知或其他值?

13

我有一个JSON API,返回一个看起来像这样的对象:

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

为了实现这一点,我拥有一个枚举和一个结构体:

#[derive(Eq, PartialEq, Deserialize, Serialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum PortType {
    Sctp,
    Tcp,
    Udp,
}

#[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,
}

目前,该API仅支持PortType中列出的三种协议,但让我们假设将来添加了对DCCP的支持。 我不想因为配置选项中的未知字符串而使API客户端开始失败,他们可能没有看过这个选项。

为了解决这个问题,我添加了一个Unknown变体,其中包含一个String来表示该值:

#[derive(Eq, PartialEq, Deserialize, Serialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum PortType {
    Sctp,
    Tcp,
    Udp,
    Unknown(String),
}

这里的目标是在传入未知值时获得稍微麻烦一些的PortType :: Unknown(“dccp”)值。当然,这并没有直接实现我想要的功能 - 传递未知的“dccp”值将导致:

Error("unknown variant `dccp`, expected one of `sctp`, `tcp`, `udp`, `unknown`", line: 1, column: 55)

是否有适合我想要的操作的Serde配置,还是我应该手动编写PortTypeDeserializeSerialize实现?

4个回答

12
尝试使用 serde-enum-str
#[derive(serde_enum_str::Deserialize_enum_str, serde_enum_str::Serialize_enum_str)]
#[serde(rename_all = "snake_case")]
pub enum PortType {
    Sctp,
    Tcp,
    Udp,
    #[serde(other)]
    Unknown(String),
}

这需要更多的可见性!它解决了“可扩展”字符串枚举在双向上的问题 - 并且还允许代码以编程方式使用“to_string()”和“parse()”在字符串和枚举之间进行转换(而不是强制使用serde进行序列化)。 - Nakedible

7

这个问题已经存在了3年,但仍然没有完全解决的方案。参见 Serde #912

目前实现的功能是#[serde(other)](尚未记录在文档中)。它只能应用于单元枚举字段,这限制了它的实用性:

#[derive(Deserialize, PartialEq)]
#[serde(tag = "tag")]
enum Target {
   A(()),
   B(()),
   #[serde(other)]
   Others
}

fn main() {
    assert_eq!(Target::Others, from_str::<Target>(r#"{ "tag": "blablah" }"#).unwrap());
}

除此之外,截至本文撰写时,唯一的其他方法是编写自己的Deserialize实现。


6
我使用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<String> 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,
}

这是一个不错的技巧,但请注意它仅适用于“简单”的枚举类型,即那些没有附加值的类型。 - piegames

3

这个简单的案例应该可以用这个解决:

use serde::de::Visitor;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::from_str;

#[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,
}

#[derive(Clone, Eq, PartialEq, Serialize, Debug)]
pub enum PortType {
    Sctp,
    Tcp,
    Udp,
    Unknown(String),
}

const PORT_TYPE: &'static [(&'static str, PortType)] = &[
    ("sctp", PortType::Sctp),
    ("tcp", PortType::Tcp),
    ("udp", PortType::Udp),
];

impl From<String> for PortType {
    fn from(variant: String) -> Self {
        PORT_TYPE
            .iter()
            .find(|(id, _)| *id == &*variant)
            .map(|(_, port_type)| port_type.clone())
            .unwrap_or(PortType::Unknown(variant))
    }
}

impl<'a> From<&'a str> for PortType {
    fn from(variant: &'a str) -> Self {
        PORT_TYPE
            .iter()
            .find(|(id, _)| *id == &*variant)
            .map(|(_, port_type)| port_type.clone())
            .unwrap_or_else(|| PortType::Unknown(variant.to_string()))
    }
}

impl<'de> Deserialize<'de> for PortType {
    fn deserialize<D>(de: D) -> Result<PortType, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct PortTypeVisitor {}

        impl<'de> Visitor<'de> for PortTypeVisitor {
            type Value = PortType;

            fn expecting(
                &self,
                fmt: &mut std::fmt::Formatter<'_>,
            ) -> std::result::Result<(), std::fmt::Error> {
                fmt.write_str("We expected a string")
            }

            fn visit_str<E>(self, variant: &str) -> Result<Self::Value, E> {
                Ok(variant.into())
            }

            fn visit_string<E>(self, variant: String) -> Result<Self::Value, E> {
                Ok(variant.into())
            }
        }

        de.deserialize_string(PortTypeVisitor {})
    }
}

fn main() {
    let input = r#"
    {
      "PrivatePort": 2222,
      "PublicPort": 3333,
      "Type": "dccp"
    }
    "#;

    let result: Result<PortMapping, _> = from_str(input);

    println!("{:#?}", result);
}

我认为目前没有一种惯用的方法可以实现这个功能,但未来可能会有。

2
是的,有一种惯用的方法可以做到这一点,并且可能会在将来包含:#[serde(other)]。请参见https://github.com/serde-rs/serde/issues/912。 - piegames

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接