当我尝试将 Person.xml 解组为 POJO 并将其打印出来时,父对象打印出正常但 ChildThree.java 打印出null
?
Test.java
public class Test {
public static void main(String[] args) {
try {
File file = new File("src/xml/person.xml");
System.out.println(file.getAbsolutePath());
JAXBContext jaxbContext = JAXBContext.newInstance(Parent.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Parent parent = (Parent) jaxbUnmarshaller.unmarshal(file);
System.out.println(parent);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Person.xml
<?xml version="1.0" encoding="utf-8"?>
<Parent>
<ChildOne>1</Child>
<ChildTwo>2</Child>
<ChildThree>
<Name>3</Name>
<Age>Ten</Age>
</ChildThree>
</Parent>
Parent.java
@XmlRootElement(name = "Parent")
@XmlAccessorType(XmlAccessType.FIELD)
public class Parent {
@XmlElement
private String ChildOne;
@XmlElement
private String ChildTwo;
@XmlElement
private ChildThree ChildThree;
public String getChildOne() {
return ChildOne;
}
public void setChildOne() {
this.ChildOne = ChildOne;
}
public String getChildTwo() {
return ChildTwo;
}
public void setChildTwo() {
this.ChildTwo = ChildTwo;
}
public ChildThree getChildThree() {
return ChildThree;
}
public void setChildThree() {
this.ChildThree = ChildThree;
}
}
ChildThree.java
@XmlRootElement(name = "ChildThree")
@XmlAccessorType(XmlAccessType.FIELD)
public class ChildThree {
@XmlElement
private String Name;
@XmlElement
private String Age;
public String getName() {
return Name;
}
public void setName() {
this.Name = Name;
}
public String getAge() {
return Age;
}
public void setAge() {
this.Age = Age;
}
}
答案 0 :(得分:1)
以下内容应该有所帮助:
@XmlAccessorType(XmlAccessType.FIELD)
时,应将注释放在字段(实例变量)而不是属性(get / set方法)上,(参见:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html)。答案 1 :(得分:0)
通过替换:
来修复它@XmlElement
private ChildThree ChildThree;
使用:
@XmlElement(name = "ChildThree")
private List<ChildThree> childThree;