我有一个需要序列化为 XML 的对象,其中包含以下字段:
List<String> tags = new List<String>();
XStream 可以很好地序列化它(在一些别名之后),如下所示:
<tags>
<string>tagOne</string>
<string>tagTwo</string>
<string>tagThree</string>
<string>tagFour</string>
</tags>
就目前而言还可以,但我希望能够重命名<string>
元素,比如说,<tag>
。从 XStream 站点上的别名文档中我看不到明显的方法来做到这一点。我错过了一些明显的事情吗?
出于兴趣,我尝试在不编写自己的转换器的情况下做到这一点。基本上我只是注册一个特殊的指导版本CollectionConverter
对于某个类别的某个领域。
相关片段:
ClassAliasingMapper mapper = new ClassAliasingMapper(xstream.getMapper());
mapper.addClassAlias("tag", String.class);
xstream.registerLocalConverter(
Test.class,
"tags",
new CollectionConverter(mapper)
);
完整的例子:
import com.thoughtworks.xstream.*;
import com.thoughtworks.xstream.converters.collections.*;
import com.thoughtworks.xstream.mapper.*;
import java.util.*;
public class Test {
public List<String> tags = new ArrayList<String>();
public List<String> notags = new ArrayList<String>();
public Test(String tag, String tag2) {
tags.add(tag); tags.add(tag2);
notags.add(tag); notags.add(tag2);
}
public static void main(String[] args) {
Test test = new Test("foo", "bar");
XStream xstream = new XStream();
ClassAliasingMapper mapper = new ClassAliasingMapper(xstream.getMapper());
mapper.addClassAlias("tag", String.class);
xstream.registerLocalConverter(
Test.class,
"tags",
new CollectionConverter(mapper)
);
System.out.println(xstream.toXML(test));
}
}
未经测试,但这应该有效。不?
xstream.alias("tag", java.lang.String.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)