最近遇到了一個問題,將
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);}// 存儲到 RedisredisTemplate.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);}