Java 如何将字节反序列化回我的类对象?
我将我的类序列化为Java 如何将字节反序列化回我的类对象?,java,serialization,byte,Java,Serialization,Byte,我将我的类序列化为字节,然后我想在反序列化它的同时从中提取所有内容。我的班级是这样的: public class DataWork { private final String clientId; private final String serverId; public DataWork(final String clientId, final String serverId) { this.clientId = clientId; t
字节
,然后我想在反序列化它的同时从中提取所有内容。我的班级是这样的:
public class DataWork {
private final String clientId;
private final String serverId;
public DataWork(final String clientId, final String serverId) {
this.clientId = clientId;
this.serverId = serverId;
}
public String getClientId() {
return clientId;
}
public String getServerId() {
return serverId;
}
@Override
public String toString() {
return "DataWork [clientId=" + clientId + ", serverId=" + serverId + "]";
}
}
下面是我的serializer类,在这里我将数据工作序列化为字节,但我不知道如何在反序列化时从中提取所有内容?一般来说,我希望在使用相同的字节对其进行反序列化时获得完整的数据工作对象
public class DataSerializer implements QueueSerializer<DataWork> {
// here I need to deserialize
public DataWork deserialize(byte[] buffer) {
// don't know what should I do here?
// buffer will have my actual bytes of DataWork
}
// here I am serializing
public byte[] serialize(DataWork work) {
return work.toString().getBytes();
}
}
公共类DataSerializer实现QueueSerializer{
//这里我需要反序列化
公共数据工作反序列化(字节[]缓冲区){
//不知道我在这里该怎么办?
//缓冲区将有我的实际字节的数据工作
}
//我在这里连载
公共字节[]序列化(数据工作){
返回work.toString().getBytes();
}
}
现在这意味着我需要以这样的方式序列化它,以便在反序列化时能够正确地从中提取所有内容。查看您的
toString()
方法实现。它将以相同的方式返回字节
// here I need to deserialize
public DataWork deserialize(byte[] buffer) {
if(null == buffer || buffer.length == 0)
return null;
// reconstruct the string back from bytes.
String data = new String(buffer);
// now just parse the string and create a new object of type DataWork
// with clientID and serverID field values retrieved from the string.
String splitData = data.split(",");
String clientID = splitData[0].split("=")[1];
String serverID = splitData[1].split("=")[1];
return new DataWork(clientID, serverID.substring(0, serverID.length() -1));
}
注意:最好使用最小分隔符序列化数据,否则解析将变得像您的情况一样麻烦。此外,它还将最小化存储或传输所需的空间。您应该明确指定字符编码,而不是使用系统特定的默认值。否则,由于不可映射字符或用于序列化和反序列化的编码不匹配,您将面临数据丢失的风险。