• SpringBoot中Redis配置类报错处理Unexpected_token(START_OBJECT)


    一、redisTemplate获取时报错:

    Caused by: com.fasterxml.jackson.databind.JsonMappingException:
    Unexpected token (START_OBJECT), expected START_ARRAY:
    need JSON Array to contain As.WRAPPER_ARRAY type information for class java.lang.Object

    二、报错代码行:

    Object obj = redisTemplate.opsForValue().get(key);
    

    三、找到配置类,注释掉这一行:

    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
    

    完整的配置

    @Bean
    	public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
    		log.info(" --- redis config init --- ");
    		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =jacksonSerializer();
    		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
    		redisTemplate.setConnectionFactory(lettuceConnectionFactory);
    		RedisSerializer<?> stringSerializer = new StringRedisSerializer();
    		// key序列化
    		redisTemplate.setKeySerializer(stringSerializer);
    		// value序列化
    		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    		// Hash key序列化
    		redisTemplate.setHashKeySerializer(stringSerializer);
    		// Hash value序列化
    		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
    		redisTemplate.afterPropertiesSet();
    		return redisTemplate;
    	}
    
    	private Jackson2JsonRedisSerializer jacksonSerializer() {
    		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    		ObjectMapper objectMapper = new ObjectMapper();
    		objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
    		// 保留这行会报错:Unexpected token (VALUE_STRING)
    		//objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
    		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    		return jackson2JsonRedisSerializer;
    	}
    
  • 相关阅读:
    类名+函数名(参数1,参数2.....){.......return this;}
    报错!无法从静态上下文中引用非静态 变量
    ERROR无法从静态上下文中引用非静态变量
    字符编码笔记:ASCII,Unicode和UTF-8
    MySQL其他类型常用函数
    MySQL流程函数
    MySQL日期和时间函数
    MySQL数值函数
    MySQL字符串函数
    MySQL位运算符优先级
  • 原文地址:https://www.cnblogs.com/eternityz/p/15329988.html
Copyright © 2020-2023  润新知