(一)序列化

@Override
public byte[] serialize(String topic, Object data) {
byte[] dataArray = null;
try {
//1、创建OutputStream对象
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//2、创建OutputStream的包装对象ObjectOutputStream,PS:对象将写到OutputStream流中
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//3、将对象写到OutputStream流中
objectOutputStream.writeObject(data);
//4、将OutputStream流转换成字节数组
dataArray = outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return dataArray;
}

(二)反序列化

@Override
public Object deserialize(String topic, byte[] data) {
Object object = null;

try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
object = objectInputStream.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
return object;
}