JAXB Marshalling shared list with variable root element name

So, I'm trying to marshal a generic list of objects, but I want every list to have a specific XmlRootElement (name ..). The way I do this, I know that it is impossible to do this without calling a specific wrapper class for each type of object and declaring an XmlRootElement. But maybe there is 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 gives:

 <entityList> <user> <username>user1</username> </user> <user> <username>user2</username> </user> </entityList> 

I want to be able to change this tag name, depending on the type of Entity I am creating an EntityList with.

I know that we are talking about compilation and start-up time here, but maybe there is some hacker way to change the shell of the parent element from the child?

+6
source share
1 answer

You can wrap an EntityList instance in a JAXBElement to provide the name of the root element at runtime.

Example

+3
source

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


All Articles