1
這裏我有兩個班「學生」和「課程」:序列化的HashMap就像一個集合屬性
@XmlRootElement
class Student {
private String name;
private HashMap<String, Course> courses;
public Student() {}
public Student(String name, HashMap<String, Course> courses) {
super();
this.name = name;
this.courses = courses;
}
// -------------------------getters
@XmlAttribute(name="name")
public String getName() {
return name;
}
@XmlElement(name = "course")
public HashMap<String, Course> getCourses() {
return courses;
}
//---------------------------setters
public void setName(String name) {
this.name = name;
}
public void setCourses(HashMap<String, Course> courses) {
this.courses = courses;
}
}
@XmlRootElement
class Course {
private String id;
private String name;
public Course() {}
public Course(String id, String name) {
super();
this.id = id;
this.name = name;
}
@XmlID
@XmlAttribute(name = "id")
public String getId() {
return id;
}
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
我想使用JAXB標註Student類序列化到像下面這樣:
<Student name="David">
<courses>
<Course id="1" name="Fundamentals of Programming"/>
<Course id="2" name="Advanced Programming">
</courses>
</Student>
請注意,我希望學生的課程字段是HashMap,並且在編組序列化對象時使用ID作爲每個課程的關鍵字。