I am trying to create an @XmlAdapter to split words in a mixed List into objects of a Wrapper class called Word. This field may also contain instances of an extension of Word called Group.
The idea is that this:
<span>Some text and a <g>group of words</g> and more<span>
would be equivalent to:
span.getContent().add(new Word("Some");
span.getContent().add(new Word("text");
span.getContent().add(new Word("and");
span.getContent().add(new Word("a");
span.getContent().add(new Group("group of words");
span.getContent().add(new Word("and");
span.getContent().add(new Word("more");
I am fighting with all the possible combinations ox XmlMixed and XmlAdapter I can think of but no luck!
This is my latets adapter which doesn't work at all:
public class SpanAdapter extends XmlAdapter<List<Word>, List> {
@Override
public List<Word> marshal(List v) throws Exception {
List<Word> list = new ArrayList<>();
for (Object o : v) {
if (o instanceof String) {
String s = (String) o;
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreElements()) {
Word word = new Word();
word.setValue(st.nextToken());
list.add(word);
}
} else if (o instanceof Group) {
list.add((Group) o);
}
}
return list;
}
@Override
public List unmarshal(List<Word> v) throws Exception {
List list = new ArrayList<>();
for (Word w : v) {
if(w instanceof Group){
list.add(w);
} else{
list.add(w.getValue()+ " ");
}
}
return v;
}
}
And my span class:
@XmlRootElement(name = "span")
public class Span extends AudioComponent implements Item.Component {
private List<Word> value = new ArrayList();
@XmlMixed
@XmlElementRefs({
@XmlElementRef(type = Group.class),
@XmlElementRef(type = Word.class)
})
@XmlJavaTypeAdapter(SpanAdapter.class)
public List<Word> getValue() {
return value;
}
public void setValue(List<Word> value) {
this.value = value;
}
}
Word and Group are just wrappers of String. Group extends Word.
I am using MOXY in case it helps.
Thank you in advance!