Using JAXB XmlAdapter to adapt an entire list without a wrapper element

I am trying to use the XmlAdapter for unmarshal XML in a custom collection type (which intentionally does not implement the Collection interface due to the conflicting restriction imposed by another use of the class, unfortunately, if the class contains any collections). The difficulty is that the XML nodes that will be placed in the collection will not be wrapped in a wrapper element.

This is what my XML looks like:

 <xml> <foo></foo> <bar>1</bar> <bar>2</bar> </xml> 

I can make JAXB unmarshall this with the following POJO :

 class Naive { Foo foo; List<Bar> bar; } 

However, I want to do the following:

 class Bars { // There will be a fixed number of these, known in advance Bar bar1; Bar bar2; } class BarsAdapter extends XmlAdapter<ArrayList<Bar>, Bars> { ... } class Custom { Foo foo; @XmlJavaTypeAdapter(BarsAdapter.class) // won't work Bars bar; } 

As you can see, I wrote an XmlAdapter that wants to adapt the entire list, not the individual elements, but it is never called for unmarshalling. (It is called to sort.)

If my XML contains a wrapper around the <bar> elements, then I know how to solve this:

 <xml> <foo></foo> <wrapper> <bar>1</bar> <bar>2</bar> </wrapper> </xml> 

because then I could annotate the bars field with @XmlElement(id="wrapper") and the adapter will be called correctly. However, the XML comes from the RFC and is completely unchanged, so I stick with the way. Any ideas appreciated!

+4
source share

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


All Articles