The goal is to produce the following XML with JAXB
<foo>
<bar>string data</bar>
<bar>binary data</bar>
</foo>
Is there a workaround to allow generic @XmlValue fields (I need to store byte[] and String data)? Below is what I desire:
@XmlRootElement
public class Foo {
private @XmlElement List<Bar> bars;
}
@XmlRootElement
public class Bar<T> {
private @XmlValue T value; // (*)
}
But I get this exception
(*) IllegalAnnotationException:
@XmlAttribute/@XmlValue need to reference a Java type that maps to text in XML.
You could leverage an
XmlAdapterfor this use case instead of@XmlValue:BarAdapter
Foo
The
XmlAdapteris associated with thebarsproperty using the@XmlJavaTypeAdapterannotation:Bar
Demo
You can test this example using the following demo code:
Output
Note how the output includes the
xsi:typeattributes to preserve the type of the value. You can eliminate the thexsi:typeattribute by having yourXmlAdapterreturnStringinstead ofObject, if you do this you will need handle the conversion fromStringto the appropriate type yourself for the unmarshal operation: