父类Student.class
import javax.xml.bind.annotation.XmlSeeAlso;
//使用@XmlSeeAlso注解: 您需要在父类上使用@XmlSeeAlso注解,
//将所有可能的子类添加到注解中,以告知JAXB在处理对象时考虑这些子类。
@XmlSeeAlso({Student1.class,Student2.class})
public class Student {
}
子类Student1.class
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")//从父类进行xml解析时,名字设定
public class Student1 extends Student{
private String name;
public Student1() {
}
@XmlElement(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
子类Student2.class
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")
public class Student2 extends Student{
private String name;
public Student2() {
}
@XmlElement(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Person类
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Person")
public class Person {
private String id;
private Student student;
public Person() {
}
@XmlElement(name = "Id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//在JAXB中,如果你有一个包含多个不同子类实例的集合,并且希望能够正确地将这些子类实例反序列化回对象,
//并且在序列化时能够正确地指定实际子类的元素名称,就可以使用@XmlElementRef。
//这个注解通常与@XmlSeeAlso注解一起使用,后者用于指定在多态性情况下JAXB需要处理的可能的子类。
@XmlElementRef
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
测试用例
@Test
public void jaxb(){
Person person = new Person();
person.setId("001");
Student1 s1 = new Student1();
s1.setName("zs");
person.setStudent1(s1);
Student1 s2 = new Student1();
s2.setName("ls");
person.setStudent2(s2);
JAXBContext context;
try {
context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(person, System.out);
} catch (JAXBException e) {
System.out.println(e);
e.printStackTrace();
}
}
结果
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Person>
<Id>001</Id>
<Student>
<Name>zs</Name>
</Student>
<Student>
<Name>ls</Name>
</Student>
</Person>
583





