溫馨提示×

python怎么反序列化java對象

小億
173
2023-12-26 22:45:53
欄目: 編程語言

要在Python中反序列化Java對象,首先需要將Java對象以某種方式序列化為字節流。然后,可以使用Python中的pickle模塊進行反序列化。

以下是一個示例,演示了如何在Java中將對象序列化為字節流,然后在Python中使用pickle模塊進行反序列化:

Java代碼(將對象序列化為字節流):

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();
        }
    }
}

運行上述Java代碼將會生成一個名為person.ser的文件,其中包含序列化的Person對象。

Python代碼(反序列化Java對象):

import pickle

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

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

在Python中,使用pickle模塊的load()函數可以從字節流中加載反序列化的對象。將字節流的文件名傳遞給open()函數,然后使用pickle.load()讀取該文件并返回反序列化的對象。

請確保在運行Python代碼之前,已經通過Java代碼序列化了Person對象并生成了person.ser文件。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女