I am trying to marshall a list of objects implementing a common interface.
There are 3 classes and 1 interface involved:
Community class (has one method: List<Person> getPeople();)
Person interface (has one method: String getName();)
Girl class (implements Person)
Boy class (implements Person)
See code below.
I want an XML that looks something like this:
<community>
<people>
<girl>
<name>Jane</name>
</girl>
<boy>
<name>John</name>
</boy>
<girl>
<name>Jane</name>
</girl>
<boy>
<name>John</name>
</boy>
</people>
</community>
or possibly:
<community>
<people>
<person>
<girl>
<name>Jane</name>
</girl>
</person>
<person>
<boy>
<name>John</name>
</boy>
</person>
</people>
</community>
So far what I get is this:
<community>
<people>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="girl">
<name>Jane</name>
</person>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="boy">
<name>John</name>
</person>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="girl">
<name>Jane</name>
</person>
<person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="boy">
<name>John</name>
</person>
</people>
</community>
I realize I can change the element to something else, but I want the element name to be the name spesified in the Girl or Boy class.
Can this be done? Thanks.
@XmlRootElement(name = "community")
public class Community {
private List<Person> people;
@XmlElementWrapper
@XmlElement(name="person")
public List<Person> getPeople() {
return people;
}
public Community() {
people = new ArrayList<Person>();
people.add(new Girl());
people.add(new Boy());
people.add(new Girl());
people.add(new Boy());
}
}
@XmlRootElement(name = "girl")
public class Girl implements Person {
@XmlElement
public String getName() {
return "Jane";
}
}
@XmlRootElement(name = "boy")
public class Boy implements Person {
@XmlElement
public String getName() {
return "John";
}
}
@XmlJavaTypeAdapter(AnyTypeAdapter.class)
public interface Person {
public String getName();
}
public class AnyTypeAdapter extends XmlAdapter<Object, Object> {
@Override
public Object marshal(Object v) throws Exception {
return v;
}
@Override
public Object unmarshal(Object v) throws Exception {
return v;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…