我有一个看起来像的XML
<Record>
<Student>
<name>sumit</name>
<rollno>123</rollno>
<Student>
<Record>
模型类看起来像
class Record{
@JsonProperty("person")
private Person person;
public String getPerson(){
return person;
}
public void setPerson(String person){
this.person=person;
}
}
abstract class Person{
@JsonProperty("name")
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
@JsonTypeName("Student")
class Student extends Person{
@JsonProperty("rollno")
private String rollno;
public String getrollno(){
return rollno;
}
public void setName(String rollno){
this.rollno=rollno;
}
}
现在在我的应用程序中,我正在从XML创建对象,如下所示
InputStream inputStream = new FileInputStream("/home/sumit/abc.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Record.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Record data = (Record) jaxbUnmarshaller.unmarshal(inputStream);
但是我在data.getPerson()中得到了null
;
有人能帮我做错事吗。
这不会按您希望的方式工作。XML元素由标记名标识,标记名需要与Java类中的字段名相对应。一旦<Record>
被建立为类Record
的值,<Student>
在该类的字段中就没有对应项,JAXB就无法对该内容进行解组。
在将<Student>
更改为<student>
之后,您应该能够使用这个修改后的类()对8进行解组
class Record{
private Student student;
public Student getStudent(){
return student;
}
public void setStudent(Student value){
student = value;
}
}
(注意,由于类Record中的Person字段的String与Person类型不匹配,还有另一个问题。)