Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB Marshalling generic list with variable root element name

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?

like image 209
user1301841 Avatar asked Mar 29 '12 21:03

user1301841


1 Answers

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

Example

  • http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/TheBasics
like image 96
bdoughan Avatar answered Nov 15 '22 00:11

bdoughan