此代码实现了从redis获取到的二进制数据转换成java对象的过程, 前提是redis中存储的是java序列化之后的java对象
java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.shiro.session.mgt.SimpleSession;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;
public class DeserializeBinaryData {
public static void main(String[] args) {
try {
// 二进制字符串,去掉空格后转换为字节数组(从redis中获取的二进制数据)
String binaryString = "1010110011101101000000000000010101110011011100100000000000...";
binaryString = binaryString.replace(" ", ""); // 移除空格
byte[] binaryData = new byte[binaryString.length() / 8];
// 将二进制字符串转换为字节数组mp-hess
for (int i = 0; i < binaryData.length; i++) {
// 每8位二进制数转换为一个字节
String byteString = binaryString.substring(i * 8, (i * 8) + 8);
binaryData[i] = (byte) Integer.parseInt(byteString, 2);
}
// 使用ByteArrayInputStream和ObjectInputStream进行反序列化
ByteArrayInputStream bis = new ByteArrayInputStream(binaryData);
ObjectInputStream ois = new ObjectInputStream(bis);
Object obj = ois.readObject();
System.err.println(obj.getClass());
if (obj instanceof ConcurrentLinkedDeque){
ConcurrentLinkedDeque obj1 = (ConcurrentLinkedDeque) obj;
System.err.println(JSON.toJSONString(obj1));
}else{
SimpleSession obj1 = (SimpleSession) obj;
Map<Object, Object> attributes = obj1.getAttributes();
System.err.println(JSON.toJSONString(attributes, SerializerFeature.PrettyFormat));
// 打印反序列化的对象
System.out.println("反序列化的对象: " + obj);
}
ois.close();
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
}