How to deserialize Java objects in Python?

In order to deserialize Java objects in Python, the Java objects must first be serialized into a byte stream in some way. Then, deserialization can be done using the pickle module in Python.

The following example demonstrates how to serialize an object into a byte stream in Java, and then deserialize it using the pickle module in Python.

Java code (serialize object into byte stream):

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Person person = new Person("John", 30);

        try {
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved in person.ser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Executing the above Java code will generate a file named person.ser, which contains a serialized Person object.

Python code (deserialize Java objects):

import pickle

with open("person.ser", "rb") as file:
    person = pickle.load(file)

print(person.name)  # 输出:John
print(person.age)  # 输出:30

In Python, you can load deserialized objects from a byte stream using the load() function from the pickle module. Simply pass the filename of the byte stream to the open() function, and then use pickle.load() to read the file and return the deserialized object.

Please make sure that the Person object has been serialized through Java code and the person.ser file has been generated before running the Python code.

Leave a Reply 0

Your email address will not be published. Required fields are marked *