Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using derived classes when marshelling with jaxb

Tags:

java

jaxb

I have a list of objects with a common base class that I am trying to serialise as XML using jaxb. I would like the annotations of the derived classes to be used when marshalling, but I'm having trouble getting there.

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:

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

However, the code above is giving:

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

Is there any way to force it to use the derived class? In the real situation I don't know ahead of time the classes that may derive from Base.

Note that I only need to marshal, not unmarshal the data.

like image 582
ICR Avatar asked Oct 10 '22 16:10

ICR


1 Answers

You can use the @XmlElementRef annotation to handle this use case. @XmlElementRef corresponds to the concept of substitution groups in XML schema.

For an Example:

  • http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-using-substitution.html
like image 159
bdoughan Avatar answered Oct 28 '22 19:10

bdoughan