我正在使用一个生成这种类型的 XML 的系统:
<address>
<addressLine>123 Main Street</addressLine>
<addressLine>Suite 123</addressLine>
<city>Test City</city>
<stateOrProvince>AA</stateOrProvince>
<postalCode>00000</postalCode>
</address>
这两个 addressLine 元素应该是 XStream 隐式集合的一部分 - 我想调用一个 getAddressLine()
方法并得到一个List<String>
输出。
我一直在使用 XStream 的教程,但还没有完全弄清楚如何获得 addressLine
要正确映射的元素。 XStream's Tweaking Output tutorial 中有一个类似的用例,但没有提供示例代码:
Another use case are collections, arrays and maps. If a class has a field that is a one of those types, by default all of its elements are embedded in an element that represents the container object itself. By configuring the XStream with the
XStream.addImplicitCollection()
,XStream.addImplicitArray()
, andXStream.addImplicitMap()
methods it is possible to keep the elements directly as child of the class and the surrounding tag for the container object is omitted. It is even possible to declare more than one implicit collection, array or map for a class, but the elements must then be distinguishable to populate the different containers correctly at deserialization.In the following example the Java type representing the farm may have two containers, one for cats and one for dogs:
<farm> <cat>Garfield</cat> <cat>Arlene</cat> <cat>Nermal</cat> <dog>Odie</dog> </farm>
然而,这 SO answer表明 XStream 农场示例是不可能的。
我已尝试使用此 Java 代码对我的 Java 代码进行单元测试,但还没有成功:
XStream xstream = new XStream(new StaxDriver());
xstream.alias("address", Address.class);
xstream.alias("addressLine", String.class);
xstream.addImplicitCollection(Address.class, "addressLines");
Address address = (Address) xstream.fromXML(
new FileInputStream("src/test/resources/addressTest.xml"));
还有我应该尝试的任何其他配置更改吗?
注意:我目前使用的是 XStream v1.2.2。
最佳答案
首先,如果可能,您应该升级到更新的 XStream - 1.2.2 于 2007 年发布。但要回答您的问题,请尝试:
XStream xstream = new XStream(new StaxDriver());
xstream.alias("address", Address.class);
xstream.addImplicitCollection(Address.class, "addressLines", "addressLine", String.class);
这表示将名称为 addressLine
的所有元素都视为字符串,并将它们收集到 addressLines
集合中(即 someAddress.getAddressLines()
).
关于java - XStream 隐式集合配置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12681397/