在尝试使用 rust 中的 serde 序列化任何嵌套的 Enum-struct/newtype-variant 时,我收到此 “无法序列化 Newtype Variant” 错误。 单位变体似乎工作很好。
这是确切的错误:
<Val/>
Val
Val
<Data>99</Data>
Data(99)
Data(99)
<Test><num>100</num><st>Please work...</st><o>Val</o></Test>
Test { num: 100, st: "Please work...", o: Val }
Test { num: 100, st: "Please work...", o: Val }
thread 'main' panicked at lib/src/main.rs:98:28:
called `Result::unwrap()` on an `Err` value: Unsupported("cannot serialize enum newtype variant `Example::Data`")
stack backtrace:
如您所见,枚举能够自行序列化,没有任何问题,并且单元枚举在结构体中也能正常工作。但是,newtype/struct 变体枚举给出了问题。
这是我的代码:
注意:这只是重现问题的示例。
use serde::{
ser::{SerializeStruct, SerializeStructVariant, SerializeTupleVariant, Serializer},
Deserialize, Serialize,
};
use quick_xml::{de::from_str, se::to_string};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Test {
num: u8,
st: String,
o: Example,
}
// commented out to show that my implementation is not the issue
//
// impl Serialize for Test {
// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
// where
// S: Serializer,
// {
// let mut state = serializer.serialize_struct("Test", 3)?;
// state.serialize_field("num", &self.num)?;
// state.serialize_field("st", &self.st)?;
// state.serialize_field("o", &self.o)?;
// state.end()
// }
// }
#[derive(Debug, Clone, Serialize, Deserialize)]
enum Example {
Val,
Data(u8),
}
// commented out to show that my implementation is not the issue
// impl Serialize for Example {
// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
// where
// S: Serializer,
// {
// match *self {
// Example::Val => serializer.serialize_unit_variant("Example", 0, "Val"),
// Example::Data(n) => serializer.serialize_newtype_variant("Example", 1, "Data", &n),
// }
// }
// }
fn main() {
// works fine
let x = Example::Val;
let sr = to_string(&x).unwrap();
let ds: Example = from_str(&sr).unwrap();
println!("{}", sr);
println!("{:?}", x);
println!("{:?}\n", ds);
// works fine
let x = Example::Data(99);
let sr = to_string(&x).unwrap();
let ds: Example = from_str(&sr).unwrap();
println!("{}", sr);
println!("{:?}", x);
println!("{:?}\n\n", ds);
// works fine
let y = Test {
num: 100,
st: "Please work...".to_owned(),
o: Example::Val,
};
let sr = to_string(&y).unwrap();
let ds: Test = from_str(&sr).unwrap();
println!("{}", sr);
println!("{:?}", y);
println!("{:?}\n", ds);
// doesn't work
let y = Test {
num: 100,
st: "Please work...".to_owned(),
o: Example::Data(99),
};
let sr = to_string(&y).unwrap();
let ds: Test = from_str(&sr).unwrap();
println!("{}", sr);
println!("{:?}", y);
println!("{:?}", ds);
}
有人建议我编写自己的序列化器并尝试这样做。但问题仍然存在,这就是我注释掉我的实现的原因。
我正在使用 fast-xml crate 编写 XML 解析器和生成器(这只是为了重现问题而编写的一小段代码)。
我尝试询问 chatgpt、文档和我的一些同事...但找不到任何解决方案或确切的问题。