我如何支持 Serde 枚举的未知值或其他值?
How can I support an unknown or other value for a Serde enum?
我有一个 JSON API returns 一个看起来像这样的对象:
{
"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 的客户端仅仅因为他们可能没有查看的配置选项中的未知字符串而开始失败。
为了解决这个问题,我添加了一个带有 String
的 Unknown
变体来表示值:
#[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 配置可以做我想做的事,或者我应该为 PortType
手动编写 Deserialize
和 Serialize
实现?
简单的案例应该没问题:
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);
}
我不认为有一种惯用的方法可以做到这一点,将来可能会包括在内。
这有一个问题,虽然它已经开放了 3 年,但到目前为止还没有完全解决。 Serde #912.
在 post 时,当前实施的(尽管未记录)似乎是 #[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
实现。
我用 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,
}
尝试使用 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),
}
我有一个 JSON API returns 一个看起来像这样的对象:
{
"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 的客户端仅仅因为他们可能没有查看的配置选项中的未知字符串而开始失败。
为了解决这个问题,我添加了一个带有 String
的 Unknown
变体来表示值:
#[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 配置可以做我想做的事,或者我应该为 PortType
手动编写 Deserialize
和 Serialize
实现?
简单的案例应该没问题:
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);
}
我不认为有一种惯用的方法可以做到这一点,将来可能会包括在内。
这有一个问题,虽然它已经开放了 3 年,但到目前为止还没有完全解决。 Serde #912.
在 post 时,当前实施的(尽管未记录)似乎是 #[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
实现。
我用 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,
}
尝试使用 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),
}