[SpringBoot2.6.13]FastJsonHttpMessageConverter不生效

文章目录

    • 错误描述
    • 问题分析
      • 打印目前所有的消息处理器
      • 寻找适配版本
      • 消息解释器加载顺序
    • 错误原因
    • 正确写法
      • 使用最新版本fastjson(2024-1-22)
      • 配置fastjson2消息转换器(保留系统原消息转换器)
      • 替换消息转换器配置fastjson2

错误描述

采用@Bean的方式配置FastJsonHttpMessageConverter消息解释器,实测在【SpringBoot2.6.13】未生效
但是在【SpringBoot2.1.4.RELEASE】版本中正常
2.1.4.RELEASE中引入如下

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

配置如下

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

 
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.QuoteFieldNames,
                SerializerFeature.WriteEnumUsingName,
                SerializerFeature.DisableCircularReferenceDetect
        );


        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastConverter);
    }

问题分析

打印目前所有的消息处理器

通过打印消息处理器,发现配置并未成功

public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
            for (HttpMessageConverter<?> messageConverter : converters) {
            System.out.println(messageConverter);
        }
    }
}

得到如下输出日志

org.springframework.http.converter.ByteArrayHttpMessageConverter@1ddf42dd
org.springframework.http.converter.StringHttpMessageConverter@5c1c9881
org.springframework.http.converter.ResourceHttpMessageConverter@1c18ee69
org.springframework.http.converter.ResourceRegionHttpMessageConverter@2f99d8c
org.springframework.http.converter.xml.SourceHttpMessageConverter@65d7eea4
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@5d37aa0f
org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@6076c66
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@485c84d7

寻找适配版本

官网可知,fastjson早已停止更新,新版本需使用fastjson2
在 Spring 中集成 Fastjson2 | fastjson2 (alibaba.github.io)
引入如下

<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2-extension-spring5</artifactId>
    <version>2.0.43</version>
</dependency>

官网得到如下配置

@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //自定义配置...
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
        config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.add(0, converter);
    }
}

消息解释器加载顺序

需要将FastJsonHttpMessageConverter配置为第一位消息处理器才能得到输出
其测试过程如下

converters.add(converter);

此时得到输出为

org.springframework.http.converter.ByteArrayHttpMessageConverter@1ddf42dd
org.springframework.http.converter.StringHttpMessageConverter@5c1c9881
org.springframework.http.converter.ResourceHttpMessageConverter@1c18ee69
org.springframework.http.converter.ResourceRegionHttpMessageConverter@2f99d8c
org.springframework.http.converter.xml.SourceHttpMessageConverter@65d7eea4
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@5d37aa0f
org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@6076c66
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@485c84d7
com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@1224e1b6

实测未生效

{
  "code": 200,
  "msg": "请求成功",
  "data": {
    "loginName": null,
    "userName": "柒杉",
    "userCode": null,
    "loginDate": 1705547281595
  }
}

修改为

converters.add(0, converter);

得到输出

com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@2a667f44
org.springframework.http.converter.ByteArrayHttpMessageConverter@53ba7997
org.springframework.http.converter.StringHttpMessageConverter@3f6f9cef
org.springframework.http.converter.ResourceHttpMessageConverter@61dd1c3d
org.springframework.http.converter.ResourceRegionHttpMessageConverter@7858d31d
org.springframework.http.converter.xml.SourceHttpMessageConverter@782e6b40
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@3b65084e
org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@32d0d7eb
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@cae2a97

错误原因

在高版本中需要采用最新的fastjson2配置

正确写法

使用最新版本fastjson(2024-1-22)

<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2-extension-spring5</artifactId>
    <version>2.0.43</version>
</dependency>

配置fastjson2消息转换器(保留系统原消息转换器)

        @Override
        public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
            // 创建 FastJson 的消息转换器实例
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            // 创建 FastJson 的配置实例
            FastJsonConfig config = new FastJsonConfig();
            // 设置时间类型日期格式
            config.setDateFormat("yyyy-MM-dd HH:mm:ss");
            config.setReaderFeatures(
                    // 基于字段序列化,如果不配置,会默认基于public的field和getter方法序列化。
                    // 配置后,会基于非static的field(包括private)做序列化。
                    JSONReader.Feature.FieldBased,
                    // 支持数据映射的方式
                    JSONReader.Feature.SupportArrayToBean
            );
            config.setWriterFeatures(
                    // 显示null与空字符串
    //                JSONWriter.Feature.WriteMapNullValue,
                    // 格式化输出
                    JSONWriter.Feature.PrettyFormat,
                    // 将Long序列化为String
                    JSONWriter.Feature.WriteLongAsString
            );
    
            // 将序列化配置设置到 FastJson 配置中
            converter.setFastJsonConfig(config);
            converter.setDefaultCharset(StandardCharsets.UTF_8);
            // 创建一个媒体类型,表示支持 JSON 格式,并使用 UTF-8 编码
            List<MediaType> fastMediaTypes = new ArrayList<>();
            MediaType utf8MediaType = new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8);
            fastMediaTypes.add(utf8MediaType);
            converter.setSupportedMediaTypes(fastMediaTypes);
            // 将 FastJson 消息转换器添加到 Spring Boot 的消息转换器列表中,位置是第一个,这样确保它优先于其他消息转换器
            converters.add(0, converter);
    
        }

替换消息转换器配置fastjson2


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            // 创建 FastJson 的消息转换器实例
            FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
            // 创建 FastJson 的配置实例
            FastJsonConfig config = new FastJsonConfig();
            // 设置时间类型日期格式
            config.setDateFormat("yyyy-MM-dd HH:mm:ss");
            config.setReaderFeatures(
                    // 基于字段序列化,如果不配置,会默认基于public的field和getter方法序列化。
                    // 配置后,会基于非static的field(包括private)做序列化。
                    JSONReader.Feature.FieldBased,
                    // 支持数据映射的方式
                    JSONReader.Feature.SupportArrayToBean
            );
            config.setWriterFeatures(
                    // 显示null与空字符串
    //                JSONWriter.Feature.WriteMapNullValue,
                    // 格式化输出
                    JSONWriter.Feature.PrettyFormat,
                    // 将Long序列化为String
                    JSONWriter.Feature.WriteLongAsString
            );
    
            // 将序列化配置设置到 FastJson 配置中
            converter.setFastJsonConfig(config);
            converter.setDefaultCharset(StandardCharsets.UTF_8);
            // 创建一个媒体类型,表示支持 JSON 格式,并使用 UTF-8 编码
            List<MediaType> fastMediaTypes = new ArrayList<>();
            MediaType utf8MediaType = new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8);
            fastMediaTypes.add(utf8MediaType);
            converter.setSupportedMediaTypes(fastMediaTypes);
            // 将 FastJson 消息转换器添加到 Spring Boot 的消息转换器列表中,位置是第一个,这样确保它优先于其他消息转换器
            converters.add(0, converter);
    }
    

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/341518.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Spring Boot3整合knife4j(swagger3)

目录 1.前置条件 2.导依赖 3.配置 1.前置条件 已经初始化好一个spring boot项目且版本为3X&#xff0c;项目可正常启动。 作者版本为3.2.2最新版 2.导依赖 knife4j官网&#xff1a; Knife4j 集Swagger2及OpenAPI3为一体的增强解决方案. | Knife4j (xiaominfo.com)http…

Docker初次体验:WSL+Docker+portanier

文章目录 前言Docker是什么&#xff1f;Docker的优点Docker的使用场景&#xff1a;一件安装 Docker安装开启虚拟化安装wsl下载慢的请看这个下载成功 安装Docker修改Docker安装位置 配置Docker安装portanier&#xff08;可视化的Docker操作页面&#xff09;登录网址 总结 前言 …

2008年苏州大学837复试机试C/C++

2008年苏州大学复试机试 题目 编写程序充成以下功能: 一、从键盘上输入随机变量x的 10个取样点。X0&#xff0c;X1—X9 的值; 1、计算样本平均值 2、判定x是否为等差数列 3、用以下公式计算z的值(t0.63) 注。请对程序中必要地方进行注释 补充&#xff1a;个人觉得这个题目回忆…

Hylicos - MINI2440 - 中断控制

中断 中断源管理 中断是一种异步异常&#xff0c;CPU需要处理很多来自设备的中断请求&#xff0c;而CPU引出的line只有IRQ线和FIQ线&#xff0c;所以就得引入中断控制器帮助CPU搞清楚是中断的来源。 MINI2440的中断控制器&#xff0c;可以接受来自60个中断源的请求。提供这些…

解决vue 2.6通过花生壳ddsn(内网穿透)实时开发报错Invalid Host header和websocket

请先核对自己的vue版本&#xff0c;我的是2.6.14&#xff0c;其他版本未测试 起因 这两天在维护一个基于高德显示多个目标&#xff08;门店&#xff09;位置的项目&#xff0c;由于高德要求定位必须使用https服务&#xff0c;遂在本地无法获取到定位坐标信息&#xff0c;于是…

020-信息打点-红蓝队自动化项目资产侦察企查产权武器库部署网络空间

020-信息打点-红蓝队自动化项目&资产侦察&企查产权&武器库部署&网络空间 #知识点&#xff1a; 1、工具项目-红蓝队&自动化部署 2、工具项目-自动化侦查收集提取 3、工具项目-综合&网络空间&信息 演示案例&#xff1a; ➢自动化-武器库部署-F8x ➢自…

MySQL数据库查询语句之组函数,子查询语句

组函数 以组为操作单位&#xff0c;一组数据得到一个结果。 在没有手动分组的前提下&#xff0c;整张表默认为一组数据 max(列名)&#xff1a;获取最大值 min(列名)&#xff1a;获取最小值 sum(列名)&#xff1a;获取总和 avg(列名)&#xff1a;获取平均值 count(列名)&a…

Operation

contents 服务器一、相关概念1.1 云服务器与实例1.2 关于域名解析延时与80端口1.3 关于备案1.4 关于SSL证书1.5 关于SSL证书的签发1.6 关于SSL证书的部署1.7 关于LNMP和LAMP1.8 关于bt面板 二、单服务器单一级域名多网站2.1 创建多个二级域名2.2 解析二级域名绑定到服务器上2.3…

夜视成像应用激光照明方法

在夜视成像领域&#xff0c;激光照明的使用主要集中在提高成像质量和远距离观察上。 以下是几种用于夜视成像的激光照明方法&#xff1a; 直接激光照明&#xff1a; 这种方法涉及直接用激光光束照射目标。激光器发出的光束可以是可见光或红外光&#xff0c;具体取决于应用需求和…

day01 深度学习介绍

目录 1.1深度学习介绍 1.2神经网络NN 1、概念&#xff1a; 2、神经元 3、&#xff08;单层&#xff09;神经网络 4、感知机&#xff08;两层&#xff09; 5、多层神经网络 6、激活函数 &#xff08;1&#xff09;饱和与非饱和激活函数 &#xff08;2&#xff09;饱和激活…

项目工时统计成本核算管理

技术架构: Java 1.8 MySQL 8 Vue 项目基于前后端分离架构&#xff0c;服务端主要技术&#xff1a;SpringBoot 前端主要是Vue。 项目介绍&#xff1a; 轻量级项目工时统计系统&#xff0c;是目前企业进行项工时管理统计的推荐选择。 通过项目工时管理系统&#xff0c;可通过…

Linux--文件链接

目录 1.建立软连接 2.建立硬链接 3.什么是软链接 Linux中软链接的应用场景 4.什么是硬链接 5.文件与目录的硬链接数 6.软链接与硬链接的区别 用户无法对目录建立硬链接&#xff0c;可以建立软连接。 在Linux中文件的链接有两种&#xff1a;1.软连接 2.硬链接 1.建立软…

Docker 配置 Gitea + Drone 搭建 CI/CD 平台

Docker 配置 Gitea Drone 搭建 CI/CD 平台 配置 Gitea 服务器来管理项目版本 本文的IP地址是为了方便理解随便打的&#xff0c;不要乱点 首先使用 docker 搭建 Gitea 服务器&#xff0c;用于管理代码版本&#xff0c;数据库选择mysql Gitea 服务器的 docker-compose.yml 配…

RK3568 移植Ubuntu

使用ubuntu-base构建根文件系统 1、到ubuntu官网获取 ubuntu-base-18.04.5-base-arm64.tar.gz Ubuntu Base 18.04.5 LTS (Bionic Beaver) 2、将获取的文件拷贝到ubuntu虚拟机,新建目录,并解压 mkdir ubuntu_rootfs sudo tar -xpf u

用flinkcdc debezium来捕获数据库的删除内容

我在用flinkcdc把数据从sqlserver写到doris 正常情况下sqlserver有删除数据&#xff0c;doris是能捕获到并很快同步删除的。 但是我现在情况是doris做为数仓&#xff0c;数据写到ods&#xff0c;ods的数据还会通过flink计算后写入dwd层&#xff0c;所以此时ods的数据是删除了…

SPN 泄露 | 扫描 | 维护

SPN 泄露 当Service Principal Names&#xff08;SPNs&#xff09;泄露时&#xff0c;可能会引发严重的安全风险&#xff0c;特别是在使用Kerberos身份验证的环境中。 身份欺骗&#xff08;Identity Spoofing&#xff09;&#xff1a; 攻击者可以用泄露的SPN来伪装成合法的服…

芯驰E3340软件编译以及更新步骤

打开已有工程File->Open Solution: 东南项目&#xff1a;e3340\boards\e3_324_ref_display\proj\jetour-t1n-fl3\sf\SES 编译&#xff1a;build->build sf 增加头文件和宏定义&#xff1a; 编译完成sf后&#xff0c;进行编译bootloader 东南项目&#xff1a;e3340\boa…

Java Server-Sent Events通信

Server-Sent Events特点与优势 后端可以向前端发送信息&#xff0c;类似于websocket&#xff0c;但是websocket是双向通信&#xff0c;但是sse为单向通信&#xff0c;服务器只能向客户端发送文本信息&#xff0c;效率比websocket高。 单向通信&#xff1a;SSE只支持服务器到客…

go语言(十四)----反射

变量的结构 2 举个例子 package mainimport "fmt"type Reader interface {ReadBook() }type Writer interface {WriteBook() }//具体类型 type Book struct {}func (this *Book) ReadBook() {fmt.Println("Read a Book")}func (this *Book) WriteBook() {…

​《WebKit 技术内幕》学习之九(3): JavaScript引擎

3 JavaScriptCore引擎 3.1 原理 JavaScriptCore引擎是WebKit中的默认JavaScript引擎&#xff0c;也是苹果在开源WebKit项目之后&#xff0c;开源的另外一个重要的项目。同其他很多引擎一样&#xff0c;在刚开始的时候它的主要部分是一个基于抽象语法树的解释器&#xff0c;这…
最新文章