JAXB Marshalling Child Class Inheritance

I have an object (Department) that will be the root element. It has an aggregated object (Employee) that has two specializations (Manager and FactoryWorker). If I set Employee to one of the custom objects, then the attributes of the Employee object are sorted. Any advice would be appreciated.

eg.

@XmlRootElement(name="department")
class Department {
   public Department() {}
   private Employee employee;
   public void setEmployee(final Employee val) {
       this.employee = val;
   }
}

class Employee {
   private Long id;
   public Employee() {}
   //getters and setters
}

class Manager extends Employee {
   public Manager() {}
   private Integer numberOfProjects;
   //getters and setters
}
class FactoryWorker extends Employee {
   public FactoryWorker() {}
   private Boolean worksNights;
   //getters and setters
}

      

A snippet of code for displaying marshalling

Deparment department = new Department();
FactoryWorker factoryWorker = new FactoryWorker();
factoryWorker.setId(999);
factoryWorker.setWorksNights(true);

JAXBContext jaxBContext = JAXBContext.newInstance(Department.class);
Marshaller jaxbMarshaller = jaxBContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(department, System.out);

      

JAXB output: custom worker attribute factory does not exist. Just the values ​​in the parent Employee.

<department>
   <employee>
      <id>999</id>
    </employee>
</department>

      

+3


source to share


1 answer


You will need to do the following:

@XmlRootElement(name="Department")
class Department {
    public Department() {}
    @XmlElements({
        @XmlElement(name="Manager", type=Manager.class),
        @XmlElement(name="FactoryWorker", type=FactoryWorker.class)
    })
    private Employee employee;
    public void setEmployee(Employee val) {this.employee = val;}
}

      

which will output:



<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Department>
    <FactoryWorker>
        <id>999</id>
        <worksNights>true</worksNights>
    </FactoryWorker>
</Department>

      

demo: http://ideone.com/Gw07mI

+4


source







All Articles