解决redis序列号和反序列化问题

发布于:2025-05-01 ⋅ 阅读:(27) ⋅ 点赞:(0)

最近遇到了一个问题,将

List<Map<String, Object>>
类型数据以list形式存入到redis之后,发现取出来时数据格式完全不对,根据报错信息发现是反序列化问题,遇到类似问题,主要有两种解决方案

1.使用序列号工具

例如,Java中常用的序列化工具有Jackson、Gson等。这些工具能够将对象序列化为字符串,并能够准确地将字符串反序列化为对象。

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RedisUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String serialize(Object object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }

    public static <T> T deserialize(String json, Class<T> clazz) throws JsonProcessingException {
        return objectMapper.readValue(json, clazz);
    }
}

使用Jackson的ObjectMapper来进行序列化和反序列化操作,serialize方法将对象序列化为字符串,deserialize方法将字符串反序列化为对象

2.使用JSON字符串存储(推荐)

直接使用JSON字符串进行存储。我们可以将对象转换为JSON字符串,并存储到Redis中。当需要获取数据时,我们可以将存储的JSON字符串转换为对象。

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

// 将 List<Map<String, Object>> 转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json;
        try {
            json = objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            logger.error("在listInRedis方法中处理Redis时发生错误", e);
            throw new RuntimeException(e);
        }
        // 存储到 Redis
        redisTemplate.opsForValue().set(key, json);
// 从 Redis 获取 JSON 字符串
        String value = (String) redisTemplate.opsForValue().get(key);

        // 将 JSON 字符串转换回 List<Map<String, Object>>
        try {
            List<Map<String, Object>> listOfMaps = objectMapper.readValue(value,
                    new TypeReference<List<Map<String, Object>>>() {
                    });
            logger.info("listInRedis从redis中查询到的结果Key:{}-----::{}", key, listOfMaps);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


网站公告

今日签到

点亮在社区的每一天
去签到