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();
        }
    }
相关推荐
文丑颜不良啊12 小时前
LeetCode2981~3000题目解析
java·leetcode
nice_lcj52013 小时前
【从零理解 Spring AI · 13】RAG 要解决什么:把“闭卷考试“变成“开卷“
java·spring·检索增强·rag·spring ai·ai应用开发
pps-key14 小时前
网络攻防入门:从“黑客梦”到合法实操(生存篇)
开发语言·web安全·php
学长毕设14 小时前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
汤姆宝库14 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
这个昵称不容易15 小时前
SpringBoot 医疗病历交互系统的设计与实现:192 个 Java 文件、256 个接口、22 张表,附真实运行截图
java·springboot·毕设
驭渊的小故事16 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
Sakura_j_h_17 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q17 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider199818 小时前
Python基础语法之并发相关3
开发语言·python