有几种方法可以解决这个问题。如果您的变体很少,最简单的方法就是Deserialize
像这样简单地手动实现:
impl serde::de::Deserialize for Structs {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: serde::Deserializer,
{
deserializer.deserialize(Visitor)
}
}
struct Visitor;
impl serde::de::Visitor for Visitor {
type Value = Structs;
fn visit_map<V>(&mut self, mut visitor: V) -> Result<Structs, V::Error>
where V: serde::de::MapVisitor,
{
let s: String = try!(visitor.visit_key()).expect("got struct with no fields");
let val = match &s as &str {
"name" => {
Ok(Structs::Foo(Foo {
name: try!(visitor.visit_value()),
baz: {
let s: String = try!(visitor.visit_key()).expect("baz field");
assert_eq!(&s, "baz");
try!(visitor.visit_value())
},
}))
},
"baz" => {
Ok(Structs::Foo(Foo {
baz: try!(visitor.visit_value()),
name: {
let s: String = try!(visitor.visit_key()).expect("name field");
assert_eq!(&s, "name");
try!(visitor.visit_value())
},
}))
},
"quux" => {
Ok(Structs::Bar(Bar {
quux: try!(visitor.visit_value())
}))
},
other => panic!("no struct has field `{}`", other),
};
try!(visitor.end());
val
}
}
这个实现的问题是它显然不能扩展。相反,您可以做的是创建一个新Deserializer
的,您给出找到的第一个字段名称并覆盖该deserialize_map
方法以通过自定义处理各种结构MapVisitor
。
如果您觉得这是其他序列化框架支持的常见情况,请随时在serde
存储库或serde-json
存储库上发布错误报告。我确信有一种方法可以自动生成这样的实现,但它肯定不是微不足道的。