gpt4 book ai didi

java - JAXB 编码子类继承

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:43:45 26 4
gpt4 key购买 nike

我有一个对象(部门),它将成为根元素。它有一个聚合对象(Employee),它有两个特化(Manager 和 FactoryWorker)。如果我将 Employee 设置为专用对象之一,则仅编码 Employee 对象属性。我将不胜感激任何提示。

例如

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

代码片段仅用于显示编码

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 输出:工厂 worker 的特殊属性不存在。只是父 Employee 中的值。

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

最佳答案

你需要这样做:

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

将输出:

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

演示:http://ideone.com/Gw07mI

关于java - JAXB 编码子类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30218477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com