So I'm trying to marshal a generic list of objects, but i want each list to have a specific XmlRootElement(name..). The way I'm doing it, I know it's not really possible without writing a specific wrapper class for each type of object and declaring the XmlRootElement. But maybe there's another way...?
Consider the following classes:
abstract public class Entity {
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="user")
public class User extends Entity {
private String username;
public String getUsername() {
return username;
}
public void setUsername( String username ) {
this.username = username;
}
}
@XmlRootElement
public class EntityList<T extends Entity> {
@XmlAnyElement(lax=true)
private List<T> list = new ArrayList<T>();
public void add( T entity ) {
list.add( entity );
}
public List<T> getList() {
return list;
}
}
public class Test {
public static void main( String[] args ) throws JAXBException {
User user1 = new User();
user1.setUsername( "user1" );
User user2 = new User();
user2.setUsername( "user2" );
EntityList<User> list = new EntityList<User>();
list.add( user1 );
list.add( user2 );
JAXBContext jc = JAXBContext.newInstance( EntityList.class, User.class );
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal( list, System.out );
}
}
As expected, this produces:
<entityList>
<user>
<username>user1</username>
</user>
<user>
<username>user2</username>
</user>
</entityList>
What i want is to be able to modify that tag name, depending on the type of Entity i create the EntityList with.
I know we're talking compile vs run time here, but maybe there's some kind of hacky way to change the parent element wrapper from the child?
You can wrap the instance of EntityList in a JAXBElement to provide a root element name at runtime.
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With