首页 > 解决方案 > 序列化包含数据集的对象

问题描述

我正在使用带有 Java 的 Spark 2.3.1 我有一个封装数据集的对象。我希望能够序列化和反序列化这个对象。

我的代码如下:

public class MyClass implements Serializable {

    private static final long serialVersionUID = -189012460301698744L;

    public Dataset<Row> dataset;

    public MyClass(final Dataset<Row> dataset) {
        this.dataset = dataset;
    }

    /**
     * Save the current instance of MyClass into a file as a serialized object.
     */
    public void save(final String filepath, final String filename) throws Exception{
        File file = new File(filepath);
        file.mkdirs();

        file = new File(filepath+"/"+filename);
        try (final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(this);
        } 
    }

    /**
     * Create a new MyClass from a serialized MyClass object
     */
    public static MyClass load(final String filepath) throws Exception{
        final File file = new File(filepath);
        final MyClass myclass;
        try (final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
              myclass = ((MyClass) ois.readObject());
        }

        System.out.println("test 1 : "+ myclass);
        System.out.println("test 2 : "+ myclass.dataset);
        myclass.dataset.printSchema();

        return myclass;
    }      
    // Some other functions   
}

但是序列化似乎没有正确完成。load() 函数给了我以下显示:

test 1 : MyClass@520e6089
test 2 : Invalid tree; null:
null

并在 printSchema() 上抛出 java.lang.NullPointerException

我缺少什么来正确序列化我的对象?

标签: javaapache-sparkserialization

解决方案


SparkDatasets仅在用于创建这些的会话范围内才有意义。因此,序列化Dataset是完全没有意义的。

  • 如果要序列化数据,只需写入Dataset持久存储。
  • 如果您想“序列化”管道,只需继续使用采用某种形式输入并返回所需的代码(方法)Dataset。不要尝试序列化Dataset自身。

推荐阅读