solarwind
solarwind

Reputation: 337

JAXB Marshalling Child Class inheritance

I have an object (Department) which will be the root element. It has an aggregated object (Employee) which has two specialisations (Manager and FactoryWorker). If I set Employee to one of the specialised objects then only the Employee object attributes are marshalled. I'd appreciate any tips.

e.g.

@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
}

Snippet of code only to show 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: the specialised attribute of factory worker are not there. Just the values in the parent Employee.

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

Upvotes: 4

Views: 3948

Answers (1)

guido
guido

Reputation: 19194

You will need to do like this:

@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

Upvotes: 7

Related Questions