Using derived classes when marshaling with jaxb

I have a list of objects with a common base class that I'm trying to serialize as XML using jaxb. I would like the annotations of derived classes to be used in sorting, but I have problems getting them.

import java.util.Arrays;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;


public class Runner {
    @XmlRootElement(name="base")
    public static abstract class Base {
        public int baseValue;

        public Base() {
            this.baseValue = 0;
        }
    }

    @XmlRootElement(name="derived")
    public static class Derived extends Base {
        public int derivedValue;

        public Derived() {
            super();
            this.derivedValue = 1;
        }
    }

    @XmlRootElement(name="derived2")
    public static class Derived2 extends Base {
        public int derivedValue;

        public Derived() {
            super();
            this.derivedValue = 1;
        }
    }

    @XmlRootElement(name="base_list")
    public static class BaseList {
        public List<Base> baseList;
    }

    public static void main(String[] args) throws JAXBException {
        BaseList baseList = new BaseList();
        baseList.baseList = Arrays.asList((Base) new Derived(), (Base) new Derived());

        JAXBContext jaxbContext = JAXBContext.newInstance(BaseList.class);

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(baseList, System.out);

    }
}

I would like to:

<base_list>
    <derived>
        <baseValue>0</baseValue>
        <derivedValue>1</derivedValue>
    </derived>
    <derived2>
        <baseValue>0</baseValue>
        <derivedValue>1</derivedValue>
    </derived2>
</base_list>

However, the above code gives:

<base_list>
    <baseList>
        <baseValue>0</baseValue>
    </baseList>
    <baseList>
        <baseValue>0</baseValue>
    </baseList>
</base_list>

Is there a way to get it to use a derived class? In a real situation, I do not know in advance the classes that can be obtained from the database.

Please note that I only need to marshal and not cancel the data.

+5
source share

All Articles