Could not read JSON: Cannot construct instance of''类名""(no Creators, like default construct, exist)

使用redis存对象的时候报错了,报错信息全部的报错信息如下:

org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Cannot construct instance of `com.xkcoding.cache.redis.entity.User` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

 

是将redis中值转化为对象的时候出错了,一开始一直以为是,使用的RedisTemplate有问题,使用的serializer用错了, 配置如下:

 /**
     * 默认情况下的模板只能支持RedisTemplate,也就是只能存入字符串,因此支持序列化
     */
    @Bean
    public   RedisTemplate  redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;


       /* RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        return redisTemplate;
*/
    }

使用的实体类如下:

package com.xkcoding.cache.redis.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 

* 用户实体 *

* * @package: com.xkcoding.cache.redis.entity * @description: 用户实体 * @author: yangkai.shen * @date: Created in 2018/11/15 16:39 * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */ @Data public class User implements Serializable { private static final long serialVersionUID = 2892248514883451461L; /** * 主键id */ private Long id; /** * 姓名 */ private String name; public User(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

实现了序列化接口,get()/set()方法存在.。理论上没有问题的!!!

    后经大佬提点,在实体类中添加无参构造方法,顺利解决:

 public User(){
        
    }

分析原因:redis的这些序列化方式,使用的是无参构造函数进行创建对象set方法进行赋值,方法中存在有参的构造函数,默认存在的无参构造函数是不存在的(继承自object),必须显示的去重写.

你可能感兴趣的:(bug)