json python

python怎么反序列化java对象

小亿
140
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
看了该问题的人还看了