【问题标题】:Using XML to serialize an ArrayList of a class that has another ArrayList使用 XML 序列化具有另一个 ArrayList 的类的 ArrayList
【发布时间】:2014-02-03 21:40:29
【问题描述】:

我正在尝试使用XMLEncoder 序列化具有另一个 ArrayList 的类的 ArrayList。可以做到吗?
这是我的代码的 sn-p:

public class Model {
    private ArrayList<Student> students;
    private ArrayList<Module> modules;

    //...

    public void saveStudentsXML() throws IOException {
        XMLEncoder encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("students.xml")));
        encoder.writeObject(students);
        encoder.close();
    }
    public void loadStudentsXML() throws IOException {
        XMLDecoder decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream("students.xml")));
        students=(ArrayList<Student>)decoder.readObject();
        decoder.close();
    }
    //this works fine

    public void saveModulesXML() throws IOException {
        XMLEncoder encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("modules.xml")));
        encoder.writeObject(modules);
        encoder.close();
    }
    public void loadModulesXML() throws IOException {
        XMLDecoder decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream("modules.xml")));
        modules=(ArrayList<Module>)decoder.readObject();
        decoder.close();
    }
    //this does not

}

Module 类有另一个 Student 类的 ArrayList(每个模块都有一个注册学生列表),

private ArrayList<Student> enrolledStudents;

当我查看 XML 时,似乎没有任何关于注册学生 ArrayList 的信息。
编辑:我已经为所有实例变量创建了 setter 和 getter,除了注册的Students ArrayList。据我所知,您不能为 ArrayList 创建 setter 方法,对吗?还有其他方法可以让 XMLEncoder 对其进行编码吗?

【问题讨论】:

    标签: java xml serialization arraylist


    【解决方案1】:

    好吧,事实证明您实际上可以为 ArrayLists 创建 setter,这只是我以前从未需要做的事情,并且愚蠢地认为它无法完成。
    在意识到我没有为 ArrayList 创建 getter 或 setter 后,我尝试了这个:

    public ArrayList<Student> getEnrolledStudents() {
        return enrolledStudents;
    }
    public void setEnrolledStudents(ArrayList<Student> enrolledStudents) {
        this.enrolledStudents = enrolledStudents;
    }
    

    这就是我需要添加到 Module 类中的所有内容,之后它运行良好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-05
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 2021-05-06
      • 2011-07-25
      • 2016-08-03
      相关资源
      最近更新 更多