Problem with implicit collection collection of XStream

I work with a system that generates this type of XML:

<address> <addressLine>123 Main Street</addressLine> <addressLine>Suite 123</addressLine> <city>Test City</city> <stateOrProvince>AA</stateOrProvince> <postalCode>00000</postalCode> </address> 

The two addressLine elements must be part of the implicit XStream collection - I would like to call the getAddressLine() method and get the List<String> output.

I worked with the XStream tutorial and didn't quite understand how to correctly display addressLine elements. There is a similar use case in the XStream Tweaking Output tutorial , but the sample code is not specified:

Other use cases are collections, arrays, and maps. If a class has a field that is one of these types, by default all its elements are embedded in the element that represents the container object itself. From configuring XStream using XStream.addImplicitCollection() , XStream.addImplicitArray() , and XStream.addImplicitMap() - it is possible to save the elements directly as children of the class and the surrounding tag for the container object is omitted. It is even possible to declare more than one implicit set, array, or map for a class, but the elements must then be distinguishable to fill the various containers correctly when deserializing.

In the following example, the Java type representing the farm can have two containers, one for cats and one for dogs:

 <farm> <cat>Garfield</cat> <cat>Arlene</cat> <cat>Nermal</cat> <dog>Odie</dog> </farm> 

However, this SO answer suggests that an example XStream farm is not possible.

I tried this Java code for the unit test of my Java code, but so far have failed:

 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")); 

Are there any other configuration changes I should try?

Note. I am currently using XStream v1.2.2.

+4
source share
1 answer

First, if possible, you should upgrade to the later XStream-1.2.2, released in 2007. But to answer your question, try:

 XStream xstream = new XStream(new StaxDriver()); xstream.alias("address", Address.class); xstream.addImplicitCollection(Address.class, "addressLines", "addressLine", String.class); 

This says that treat all elements named addressLine as strings and collect them into the addressLines collection (i.e. someAddress.getAddressLines() ).

+10
source

Source: https://habr.com/ru/post/1437292/


All Articles