使用serde序列化结构时如何展平`Vec`字段? [英] How to flatten a `Vec` field when serializing a struct with serde?
问题描述
我有一些 XML 的标签包含多个同名的兄弟标签,如下所示:
I've got some XML that has a tag containing multiple sibling tags with the same name, like so:
<foo>
<bar/>
<bar/>
</foo>
(也可能有多个顶级 <foo>
,尽管我还没有尝试对其进行(反)序列化.)
(There may also be multiple top level <foo>
s as well, though I've not gotten around to trying to (de)serialize that yet.)
使用此代码:
use serde::{Deserialize, Serialize};
use quick_xml::de::from_str;
use quick_xml::se::to_string;
#[derive(Debug, Deserialize, PartialEq, Serialize)]
pub struct Foo {
#[serde(rename = "bar", default)]
bars: Vec<Bar>,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename = "bar")]
struct Bar{
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deserialize_trivial_string_test() {
let fs = "<foo><bar/><bar/></foo>";
let foo = from_str(fs).unwrap();
assert_eq!(Foo { bars: vec![Bar {}, Bar {}] }, foo);
}
#[test]
fn serialize_trivial_string_test() {
let foo = Foo { bars: vec![Bar {}, Bar {}] };
let fs = to_string(&foo).unwrap();
assert_eq!("<foo><bar/><bar/></foo>", fs);
}
}
不要忘记激活序列化功能:
and don't forget to activate serialize feature:
[dependencies.quick-xml]
version = "0.18.1"
features = ["serialize"]
我可以很好地反序列化,但是序列化添加了一个额外的
标记作为 bars
字段包装实际的
代码>标签:
I can deserialize just fine, but serialization adds in an extra <bar>
tag as the bars
field wrapping the actual <bar>
tags:
<Foo>
<bar>
<bar></bar>
<bar></bar>
</bar>
</Foo>
bars
字段上的 #[serde(rename = "bar", default)]
是我第一次尝试解决这个问题,基于 quick-xml 的文档,但它显然不起作用.我还查看了 serde 的文档,确实找到了 flatten
属性,但是当我尝试将其应用于 bars
字段时,它似乎不起作用.
The #[serde(rename = "bar", default)]
on the bars
field was my first attempt to fix the this, based on quick-xml's documentation, but it obviously does not work. I also looked through serde's documentation, and did find a flatten
attribute, but it did not seem to work when I tried applying it to the bars
field.
除了手动实现Deserialize
之外,有什么方法可以获得我需要的序列化吗?
Is there any way to get the serialization that I need, short of manually implementing Deserialize
?
如果相关,我尝试使用的实际数据格式是 flam3 文件格式.这里有一个示例文件.<flame>
元素在这里等同于
,而
等同于 <;bar>
.
In case it's relevant, the actual data format I'm trying to work with is the flam3 file format. There's a sample file here. The <flame>
element would be the equivalent to <foo>
here, and <xform>
is equivalent to <bar>
.
推荐答案
很遗憾,您不能.GitHub 上有一个未决问题可以解决您的问题.
Unfortunately you can't. There is a outstanding issue on GitHub that addresses your question.
这篇关于使用serde序列化结构时如何展平`Vec`字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!