当前位置: 首页 > news >正文

Spring Boot集成fastjson2快速入门Demo

1.什么是fastjson2?

fastjson2是阿里巴巴开发的一个高性能的Java JSON处理库,它支持将Java对象转换成JSON格式,同时也支持将JSON字符串解析成Java对象。本文将介绍fastjson2的常见用法,包括JSON对象、JSON数组的创建、取值、遍历,以及与字符串、Java对象、Map、List的相互转换。

  • 支持JSON/JSONB两种协议,JSONPath 是一等公民。
  • 支持全量解析和部分解析。
  • 支持Java服务端、客户端Android、大数据场景。
  • 支持Kotlin
  • 支持JSON Schema FASTJSON v2 JSONSchema的支持 | fastjson2
  • 支持Android
  • 支持Graal Native-Image

2.代码工程

实验目标

在 Spring Web MVC 中集成 Fastjson2

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>fastjson2</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.40</version></dependency><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2-extension-spring5</artifactId><version>2.0.40</version></dependency></dependencies>
</project>

config

使用 FastJsonHttpMessageConverter 来替换 Spring MVC 默认的 HttpMessageConverter 以提高 @RestController@ResponseBody 和 @RequestBody 注解的 JSON 序列化和反序列化速度。 配置示例如下:

package com.et.fastjson2.config;import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();//custom configurationFastJsonConfig 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);}}

controller

package com.et.fastjson2.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;@RestController
public class HelloWorldController {@RequestMapping("/hello")public Map<String, Object> showHelloWorld(){Map<String, Object> map = new HashMap<>();map.put("msg", "HelloWorld");return map;}
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo

3.测试

  • 启动spring boot工程,
  • 访问http://127.0.0.1:8088/hello
  • 返回美化的Json格式,说明生效了

4.fastjosn避坑

1.BigDecimal精度丢失问题

  @Testpublic void toJSONString() throws ParseException {UserDTO  user =  new UserDTO();BigDecimal money =new BigDecimal(-40090.07d);money = money.setScale(4, RoundingMode.HALF_UP);user.setMoney(money);String createtime ="2024-07-03 09:03:26.968";SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");Date date = format.parse(createtime);user.setCreateTime(date);List<UserDTO> list = new ArrayList<>();list.add(user);String json=JSON.toJSONString(list);System.out.println(json);}}
执行结果
[{"createTime":"2024-07-03","money":-40090.700}]

发现没有一个怪异现象:-40090.07 变成了-40090.700,直接查几毛钱,原因是fastjson处理bigdecimal不是吧它当成字符串处理,导致丢失精度

解决方法
String json=JSON.toJSONString(list,  JSONWriter.Feature.WriteBigDecimalAsPlain);

2.日期解析问题

@Test
public void parseArray()  {String json="[{\"create_time\":\"2024-07-03 09:03:26.968\",\"money\":-40090.0700}]";System.out.println(json);List<UserDTO> list1 = JSON.parseArray(json, UserDTO.class,JSONReader.Feature.SupportSmartMatch);System.out.println();
}
运行结果
java.time.format.DateTimeParseException: Text '2024-07-03 09:03:26.968' could not be parsed, unparsed text found at index 10
解决方法
UserDTO上加上@JSONField(format= "yyyy-MM-dd HH:mm:ss")

5.引用

  • JSONB格式文档: https://alibaba.github.io/fastjson2/jsonb_format_cn
  • FASTJSON v2性能有了很大提升,具体性能数据看这里: 

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【大模型LLM面试合集】大语言模型基础_NLP面试题
  • uboot学习:(一)基础认知
  • Linux运维:MySQL中间件代理服务器,mycat读写分离应用实验
  • ceph存储
  • 大语言模型应用--AI工程化落地
  • 高中数学:立体几何-基本立体图形分类
  • DAMA学习笔记(四)-数据建模与设计
  • 【分布式系统】Ceph块存储系统之RBD接口
  • 【通信协议-RTCM】系统参数消息 ---- 对应RTCM十六进制 编码ID(3F5)
  • UE5 03-物体碰撞检测
  • c++ primer plus 第15章友,异常和其他,15.3.8exception 类
  • JDK11中zgc垃圾回收器的探索
  • 【进阶篇-Day7:JAVA中Date、LocalDate等时间API的介绍】
  • 对于多个表多个字段进行查询、F12查看网页的返回数据帮助开发、数据库的各种查询方式(多对多、多表查询、子查询等)。
  • Zynq系列FPGA实现SDI视频编解码+图像缩放+多路视频拼接,基于GTX高速接口,提供8套工程源码和技术支持
  • 网络传输文件的问题
  • 【跃迁之路】【735天】程序员高效学习方法论探索系列(实验阶段492-2019.2.25)...
  • Android组件 - 收藏集 - 掘金
  • HTTP中的ETag在移动客户端的应用
  • js中的正则表达式入门
  • MaxCompute访问TableStore(OTS) 数据
  • MYSQL 的 IF 函数
  • python大佬养成计划----difflib模块
  • XForms - 更强大的Form
  • 从地狱到天堂,Node 回调向 async/await 转变
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 名企6年Java程序员的工作总结,写给在迷茫中的你!
  • 实习面试笔记
  • 使用SAX解析XML
  • 微信如何实现自动跳转到用其他浏览器打开指定页面下载APP
  • 关于Android全面屏虚拟导航栏的适配总结
  • 摩拜创始人胡玮炜也彻底离开了,共享单车行业还有未来吗? ...
  • ​VRRP 虚拟路由冗余协议(华为)
  • ​十个常见的 Python 脚本 (详细介绍 + 代码举例)
  • (01)ORB-SLAM2源码无死角解析-(66) BA优化(g2o)→闭环线程:Optimizer::GlobalBundleAdjustemnt→全局优化
  • (3)选择元素——(17)练习(Exercises)
  • (a /b)*c的值
  • (MIT博士)林达华老师-概率模型与计算机视觉”
  • (板子)A* astar算法,AcWing第k短路+八数码 带注释
  • (二)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (六)DockerCompose安装与配置
  • (七)Java对象在Hibernate持久化层的状态
  • (十二)Flink Table API
  • (顺序)容器的好伴侣 --- 容器适配器
  • (算法二)滑动窗口
  • (一)UDP基本编程步骤
  • .equals()到底是什么意思?
  • .gitignore文件_Git:.gitignore
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .net6解除文件上传限制。Multipart body length limit 16384 exceeded
  • .NetCore部署微服务(二)
  • .NET成年了,然后呢?
  • .NET开源快速、强大、免费的电子表格组件
  • .pyc文件是什么?
  • @RequestBody与@RequestParam:Spring MVC中的参数接收差异解析