java反序列化redis中的java对象

此代码实现了从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();
        }
    }
相关推荐
朦胧之7 小时前
AI 编程-老项目改造篇
java·前端·后端
程序猿大帅11 小时前
别再只当调包侠了:用 Spring AI 落地 Function Calling,我被大模型硬生生砸出了三个大坑
java
程序员晓琪12 小时前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly12 小时前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
众少成多积小致巨13 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
东坡白菜13 小时前
破局全栈:前端开发的Java入门实战记录—JPA(2)
java·后端
SimonKing19 小时前
艹,维护AI写的代码,我心态崩了......
java·后端·程序员
用户2986985301419 小时前
Java Word 文档样式进阶:段落与文本背景色设置完全指南
java·后端
小bo波1 天前
从"任意文件复制"深挖Java I/O:字符流与字节流的本质抉择
java·nio·io流·后端开发·文件复制
nanxun8862 天前
记一次诡异的 Docker 容器"串包"故障排查
java