JAXB Marshalling generic list with variable root element name

落花浮王杯 提交于 2019-12-19 18:52:46

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/9933475/jaxb-marshalling-generic-list-with-variable-root-element-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!