gpt4 book ai didi

java - 反序列化异常 : local class is not compatible cause of serialVersionID

转载 作者:行者123 更新时间:2023-11-30 09:02:44 28 4
gpt4 key购买 nike

这是我的代码:

MyOwnObject deserializedObject = null;
try{
ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject.getBytes());
ObjectInputStream ois= new ObjectInputStream(bis);
deserializedObject = (MyOwnObject)ois.readObject();
ois.close();
}catch(Exception e){
e.printStackTrace();
}

someMapper.insert(deserializedObject);

PS:serializedObject 是我之前从序列化过程中得到的一个字符串,我认为它运行良好。

代码抛出异常:

local class incompatible: stream classdesc serialVersionUID = 1360826667802527544, local class serialVersionUID = 1360826667806852920

在堆栈跟踪中,有关于我的对象中某些属性的整数类型的信息。

更新:serializeObject 是一个字符串,来自这段代码:

try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(myObject);
so.flush();
serializedObject = bo.toString();
}catch (Exception e) {
System.out.println(e);
}

回答:

    //Serialization from object to string
String serializedObject="";
try{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
serializedObject = new String(Base64.encode(baos.toByteArray()));
oos.close();
}catch(Exception e){
e.printStackTrace();
}


//Deserialization from string to object
MyOwnObject deserializedObject = null;
try{
byte[] bytes = Base64.decode(serializedObject.getBytes());
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
deserializedObject = (MyOwnObject)ois.readObject();
ois.close();
}catch(Exception e){
e.printStackTrace();
}

从这里开始,我可以将 deserializedObject 用作​​对象,而且效果很好!

最佳答案

问题在于如何创建 serializedObject

您使用一个ByteArrayOutputStream。您不应该对其调用 toString()。而是调用它的 toByteArray() 方法来获取字节数组形式的基础数据,您可以使用它来创建您的 ByteArrayInputStream,它会起作用。

例子:

// Serialization
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(myObject);
so.flush();
byte[] serializedObject = bo.toByteArray();

// Deserialization
MyOwnObject deserializedObject = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject);
ObjectInputStream ois = new ObjectInputStream(bis);
deserializedObject = (MyOwnObject)ois.readObject();
ois.close();
} catch (Exception e){
e.printStackTrace();
}

序列化对象是字节序列(字节数组)而不是字符序列。您不能从序列化对象的字节创建 String,因为它可能不包含例如有效的 unicode 代码点。

如果您确实需要将序列化对象表示为String,请尝试在hex string 中表示字节数组。或使用 base64 encoding .

关于java - 反序列化异常 : local class is not compatible cause of serialVersionID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25883984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com