SpringBoot中Redis连接池存储对象出现乱码问题的解决教程:Could not read JSON: Unexpected character (�) at position 0.

FastJSON错误Could not read JSON: Unrecognized field 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站,这篇文章男女通用,看懂了就去分享给你的码吧。 fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴的工程师开发。快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson)强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)零依赖(没有依赖其它任何类库除了JDK) 在使用FastJSON 阅读详情

前言

  SpringBoot是一个非常方便的Java开发框架,但在实际开发过程中,我们难免会遇到一些问题。这里将介绍在使用SpringBoot时,当我们将对象存储到Redis中时,出现了乱码的问题,并将会给出详细的解决方案。

问题背景

  在使用SpringBoot连接Redis的时候,我们通常会选择使用RedisTemplate来进行操作。但是,在使用RedisTemplate将一个类存储到Redis中时,有时候会出现乱码的情况,如下所示:

org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unexpected character (�) at position 0.

  这个错误提示告诉我们,RedisTemplate无法解析JSON格式的对象,并且在第一个字符位置处出现了意外的字符(即乱码)。

问题分析

  经过仔细查找,我们发现这个问题的原因是RedisTemplate默认使用JdkSerializationRedisSerializer进行序列化,而JdkSerializationRedisSerializer会将对象序列化成字节流,导致我们在取出数据后无法正常解析。

解决方案

方案一:更换序列化器

  为了解决这个问题,我们可以更换RedisTemplate的序列化器。在SpringBoot中,我们可以通过修改application.yml文件来进行配置:

spring:
  redis:
    host: localhost
    port: 6379
    password:
    timeout: 10000
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        max-wait: -1
        min-idle: 0
      shutdown-timeout: 3000
    # 更换序列化器
    keySerializer: org.springframework.data.redis.serializer.StringRedisSerializer
    valueSerializer: org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer

  这里我们将keySerializer和valueSerializer都更换为了StringRedisSerializer和GenericJackson2JsonRedisSerializer。

方案二:修改存储方式

  除了更换序列化器的方式外,我们也可以选择修改存储的方式。例如,不直接将对象存储到Redis中,而是将其转换成JSON格式再存储。示例代码如下:

@Autowired
private RedisTemplate redisTemplate;

public void setObject(String key, Object value) {
    // 将对象转换成JSON字符串
    String jsonString = JSON.toJSONString(value);
    redisTemplate.opsForValue().set(key, jsonString);
}
    
public Object getObject(String key) {
    String value = (String) redisTemplate.opsForValue().get(key);
    // 将JSON字符串转换成对象
    return JSON.parseObject(value, Object.class);
}

  这样,我们就可以正确地将对象存储到Redis中,并且在需要的时候顺利地取出。

结束语

  以上就是本次关于SpringBoot中Redis连接池存储对象出现乱码问题的解决教程,希望能够对您在实际开发中遇到类似问题时有所帮助。

Spring Boot Redis配置实战:序列化乱码、RedisTemplate单例与多例、scan获取所有key Redis作为高性能缓存和分布式数据结构存储,在Java后端开发中广泛用于缓存、分布式锁和会话共享。其核心原理是基于内存的键值存储,通过序列化将Java对象转为字节数组实现持久化。合理配置序列化器(如StringRedisSerializer和Jackson2JsonRedisSerializer)能解决客户端乱码问题,提升数据可读性和跨语言兼容性。在Spring Boot集成中,RedisTemplate默认单例,但多实例隔离或动态切换数据库时需转为多例,同时共享连接工厂避免资源浪费。获取所有key时,生 阅读详情

相关推荐

RedisTemplate存数据乱码

如果你发现存进redis的数据,key和value均是乱码,可能是因为你用redisTemplate的时候,没有配置它的序列化方式。写一个配置类,就可以啦。

赵达宇的博客 1604

redis Could not read JSON: Unexpected character (‘¬‘ (code 172)): expected a valid value (JSON St

首先说说,我碰到这个情况 我有个老项目是spring mvc的 然后用的redis 版本是1.6.2的版本,这个项目在使用中,所以redis里面存了很多登录缓存,,然后我又开了一个新项目,但是登陆是通用数据库,新项目是springboot的 用的redis是2.0.6的 那么问题出来了 Could not read JSON: Unexpected character ('¬' (code 172)) 这个异常通常是说的序列化失败 先看看springMVC的配置 <bean id="re.

qq_33563609的博客 1万+

CANoe信号波形分析保姆级教程:Graphic窗口从配置到实战避坑

本文详细解析了CANoe的Graphic窗口在信号波形分析中的高效配置与实战应用技巧。从信号显示模式选择、测量光标进阶操作到信号分组策略,提供工程化解决方案,帮助工程师快速定位总线信号异常,提升汽车电子开发与测试效率。

weixin_29279047的博客 265

redis获取缓存对象bean时报:SerializationException: Could not read JSON: Could not resolve type

关于redis缓存反序列化失败的处理

u013232219的博客 9348

【k8s实战】 在离线项目混部 通过kubeflow(tf-operator)部署TensorFlow机器学习任务+prometheus/grafana监控资源使用全过程(最新 图文)

目录在离线混合部署概念最新版kubeflow部署TensorFlow部署二级目录三级目录 在离线混合部署概念 先举一个例子,众所周知的天猫双十一当天的流量非常之大,那么就需要成百上千台服务器构成一个超大集群来提供计算能力,但是双十一过去之后,集群资源就面临着浪费的局面。假设业务分为在线和离线两种模式:在线任务需要资源相对较少,但要求响应时间短;离线任务则不需要对任务进行迅速响应,但是计算量相对较大、占用资源多。那么我们应该怎么在K8S集群上完成这两种业务的部署、并且使得CPU利用率始终维持在一个比较高的水平

Eros1on的博客 1545

DIKW模型实战:用Obsidian打造个人知识库的5个关键步骤

本文详细介绍了如何利用DIKW模型在Obsidian中构建高效个人知识库的5个关键步骤,从数据收集到智慧应用的全流程实践。通过标记系统、信息加工引擎和知识结晶方法,帮助知识工作者实现从原始数据到决策智慧的认知跃迁,提升个人知识管理效率。

gamma的博客 574

Could not read JSON: Unexpected character (‘f‘ (code 102)) in numeric value: Decimal point not follo

1.查看存储到redis的数据是字符串还是对象,对数据进行清除。2.检查写入和读取是否一致。

man_18483633325的博客 1118

WhatsApp API接口的隐秘角落:从协议解析到自定义消息引擎

本文深入解析WhatsApp API接口的隐秘角落,从协议逆向工程到自定义消息引擎开发实战。通过分析WhatsApp的二进制XML协议和加密机制,构建超越官方API限制的自定义消息引擎,实现高效、灵活的即时通讯解决方案。文章还提供了企业级架构设计和风控规避策略,助力开发者突破官方限制,提升消息到达率和成本效益。

q3r4s5t的博客 761

SpringBoot整合Redis,解决乱码问题

通常用SpringBoot整合Redis后会出现乱码问题,通常的解决方案是将Redis重新序列化加上如下配置,就不会出现xx0x3/xx9x,等键值乱码问题了

weixin_40598838的博客 1966

【WRF-Chem教程第四期上】运行 WRF-Chem 模型

完整介绍运行 WRF-Chem 模型的详细步骤

WW、forever的博客 3108

使用podspec创建iOS插件

概述 在WWDC 2014全球开发者大会上,苹果开放了动态库、App Extension等全新的功能,这为iOS插件化开发带来了可能。在iOS开发中,动态库是iOS提供的一种资源打包方式,可以将代码文件、头文件、资源文件和说明文档等集中在一起,并且可以在运行时进行动态加载。 目前,很多应用越做越复杂,应用程序也显得越来越臃肿。试想一下,如果将一些不常用的功能做成一个插件,然后根据用户的需求从网络中...

xiangzhihong8的专栏 991

Could not read JSON: Unexpected character (‘c‘ (code 99)): was expecting comma to separate OBJECT en

Could not read JSON: Unexpected character ('c' (code 99)): was expecting comma to separate OBJECT en

阿涩的博客 3564

TPM 2.0实例探索2 —— LUKS磁盘加密(1)

本文对LUKS行了系统介绍

phmatthaus的专栏 1699

SpringBoot连接Redis且解决乱码

SpringBoot连接Redis且解决乱码

李长渊的博客 1528

杰理JL703N的SDK内部MIDI 音色库功能使用教程

本文介绍了MIDI琴按键解码和MIDI文件解码的实现方法。MIDI琴解码通过audio_dec_midi_ctrl.c文件实现,MIDI文件(mfa格式)解码则使用audio_dec_midi_file.c。使用前需将音色文件存放在SD卡或内置flash中(需确保四字节对齐),并在download.c中配置路径。同时需在板级配置中将FLASH设置为16Mbit以解决编译问题。关键注意事项包括音色文件的文件夹结构对齐要求和MIDI数据流的正确配置。

qq_42014563的博客 389

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

springboot整合redis出现乱码解决方法

第一种情况 通过redisTemplate 设置值时乱码 在RedisConfig中加入序列化 // key序列化 redisTemplate.setKeySerializer(STRING_SERIALIZER); // value序列化 redisTemplate.setValueSerializer(JACKSON__SERIALIZER); // Hash key序列化 redisTemp...

鱿鱼的博客 7019

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Rredis错误 SerializationException: Could not read JSON: Unexpected character (‘¬‘ (code 172))

异常: Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('¬' (code 172)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false') 原因: set存get取序列化方式选择不一致,检查RedisConfig配置的取值序列化方式与实际存值时选择的序列化方

weixin_39690406的博客 3978

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Redis获取数据报错Could not read JSON: Unrecognized token 'XXXXX': was expecting ('true', 'false' or 'null'

日前由于公司Redis集群切换,导致一些初始化数据需要重新设置到新的Redis; 使用Redis可视化 RedisDesktopManager进行设置 设置成功,到获取的时候发生异常: 2020-04-02 15:42:05.118 yxcode-merak [http-nio-8080-exec-14] ERROR c.y.y.m.c.handle.ExceptionHandle [E...

qq_36601979的博客 1万+

springboot redis key乱码

因为spring操作redis是在jedis客户端基础上进行的,而jedis客户端与redis交互的时候协议中定义是用byte类型交互,看到spring-data-redis中RedisTemplate<K, V>在操作的时候k,v是泛型对象,而不是byte[]类型的,这样导致的一个问题就是,如果不对RedisTemplate进行设置,spring会默认采用defaultSerializer = new JdkSerializationRedisSerializer();

qq_41970652的博客 762

springboot redis Template使用,数据乱码解决

springboot提供了redis客户端,可以很方便的和springboot进行集成,一般在pom中引入: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependenc

LeoHan 1786

解决redis乱码问题

解决redis乱码问题 直接添加一个配置类就行了 /**解决redis中文乱码 * Created by dgx on 2019/8 */ @Configuration public class Config { @Autowired private RedisTemplate redisTemplate; @Bean public RedisTemp...

qq_40948117的博客 1288

Springboot的有关redis的key是乱码的问题(只是解决redis客户端识别类型和防止英文状态下的key乱码问题)

导致乱码的主要原因是在Springboot里面会先将对应的对象进行byte的转换,如果想要识别正确的类型可以设置自己的配置类进行修改,而转换方法是使用JdkSerializationRedisSerializer 的convert方法转换所以自己写一个修改对应的redisSerializaer就行,然后直接交给ioc管理就可以替换掉原来byte的配置。

学习记录 1043

Could not read JSON: java.lang.NumberFormatException: empty String;

报错信息为: Could not read JSON: java.lang.NumberFormatException: empty String; nested exception is com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: empty String java中的字段为Long userId,json报文中为""。 就报这个错了,去掉json报文中的这个字段即可。 ...

enthan809882的博客 2318

redis反序列化异常(org.springframework.data.redis.serializer.SerializationException: Could not read )

set值的时候注入了redisTemplate,get值的时候不小心注入了RedisTemplate,导致反序列化时找不到对应类型。RedisTemplate改为RedisTemplate。由此可知Redis序列化异常,不能读取Json。可是redis是做了序列化配置的,这就很奇怪了。redis反序列化异常。...

weixin_43757027的博客 3581

Redis缓存写入数据,解决Could not read JSON: Cannot construct instance of `xxx.xxDTO`的问题

2、redis 的这些序列化方式,使用的是构造函数进行创建对象。两种构造方式都可以,一种是显示写法,一种隐式写法。1、在实体类或DTO类添加无参构造方法,如下。1、序列化对象的时候出错了。

hkl_Forever的博客 1609

[Redis] Spring Boot 使用Redis---RedisTemplate泛型约束乱码问题

RedisTemplate泛型约束乱码问题解决

沫洺的博客 1447
上一篇: 面向切面编程的秘密:剖析Spring AOP实现原理
下一篇: 在公司向个人github项目提交代码却没有contributions的小绿点
JavaWizard-M
博客等级 码龄6年 3159粉丝 148原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值