org.springframework.data.redis.serializer.SerializationException: Could not read JSON: NA

tech2026-02-26  2

**

GenericJackson2JsonRedisSerializer序列化遇到的坑

**

**

问题现象

** 工程使用redis作为缓存,起初使用GenericJackson2JsonRedisSerializer作为序列化反序列化工具。一般正常的对象(set,get齐全),序列化以及解序列化都没有问题。但是一旦某个对象只有get方法,而没有set方法。就无法正常反序列化。

Redis序列化设置jackson

// hash的value序列化方式采用jackson redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); // value序列化方式采用jackson redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

测试对象

public class Demo { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGrade(){ return "grade1"; } }

留意最后一个方法 getGrade(){ return “grade1”; } 只有get

reids序列化内容

{"@class":"cn.pxwell.showen.Demo","name":"张三","age":3,"grade":"grade1"}

**

反序列化时Error提示

**

org.springframework.data.redis.serializer.SerializationException: Could not read JSON:Unrecognized field "grade" (class cn.pxwell.showen.Demo), not marked as ignorable (2 known properties: "name", "age"]) at [Source: (byte[])"{"@class":"cn.pxwell.showen.Demo","name":"张三","age":3,"grade":"grade1"}"; line: 1, column: 68] (through reference chain: cn.pxwell.showen.Demo["grade"]); nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "grade" (class cn.pxwell.showen.Demo), not marked as ignorable (2 known properties: "name", "age"]) at [Source: (byte[])"{"@class":"cn.pxwell.showen.Demo","name":"张三","age":3,"grade":"grade1"}"; line: 1, column: 68] (through reference chain: cn.pxwell.showen.Demo["grade"])

error提示: Could not read JSON: N/A

改用fastJson作为序列化工具

redis配置文件用: <property name="hashValueSerializer"> <bean class="com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer"/> </property> SpringBean用: // hash的value序列化方式采用fastJson redisTemplate.setHashValueSerializer(new GenericFastJsonRedisSerializer()); // value序列化方式采用fastJson redisTemplate.setValueSerializer(new GenericFastJsonRedisSerializer());
最新回复(0)