gpt4 book ai didi

java - 包含其他对象集合的对象的 JAXB 解码问题

转载 作者:行者123 更新时间:2023-12-04 04:49:56 25 4
gpt4 key购买 nike

我正在尝试将以下 XML 文档解码为 JAXB java 对象。

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<company>
<name>ABC Inc</name>
<address>123 1st Street, My City, AB</address>
<employees>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
<employee>
<firstName>John2</firstName>
<lastName>Doe2</lastName>
</employee>
</employees>
</company>

使用以下 java 代码,但即使 XML 包含两个元素,子集合 (company.getEmployees()) 也不包含任何元素。
    JAXBContext jc = JAXBContext.newInstance("com.abc");
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Company> root = unmarshaller.unmarshal(new StreamSource(new FileInputStream( "TestCompany.xml" )), Company.class);
Company company = root.getValue();
List<Employee> employees = company.getEmployees();

以下是 JAXB 生成的类:
    @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "company", propOrder = {
"name",
"address",
"employees"
})
public class Company {
@XmlElement(required = true)
protected String name;
@XmlElement(required = true, nillable = true)
protected String address;
protected List<Employee> employees;

public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getAddress() {
return address;
}
public void setAddress(String value) {
this.address = value;
}
public List<Employee> getEmployees() {
if (employees == null) {
employees = new ArrayList<Employee>();
}
return this.employees;
}
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "employee", propOrder = {
"firstName",
"lastName"
})
public class Employee {

@XmlElement(required = true)
protected String firstName;
@XmlElement(required = true)
protected String lastName;

public String getFirstName() {
return firstName;
}
public void setFirstName(String value) {
this.firstName = value;
}
public String getLastName() {
return lastName;
}
public void setLastName(String value) {
this.lastName = value;
}
}

最佳答案

默认情况下,JAXB 实现不会为集合添加分组元素。您需要执行以下操作并利用 @XmlElementWrapper :

@XmlElementWrapper
@XmlElement(name="employee")
protected List<Employee> employees;

更多信息
  • http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html
  • 关于java - 包含其他对象集合的对象的 JAXB 解码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17573892/

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