像集合属性一样序列化HashMap

时间:2013-05-11 08:58:59

标签: jaxb 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>

请注意,我希望Student的courses字段为HashMap,当解组序列化Object时,使用id作为每个Course的键。

1 个答案:

答案 0 :(得分:0)

您可以在此用例中使用XmlAdapterXmlAdapter允许您以编程方式将对象转换为另一种类型,以便进行编组/解组。对于您的用例,您将HashMap转换为集合为Course的对象的实例。