关于Java JSON库的选择

news/2025/12/3 20:34:04/文章来源:https://www.cnblogs.com/nuccch/p/19303901

Jackson和Fastjson(目前推荐用fastjson2)都是Java平台非常流行的JSON库,它们在性能方面不分伯仲,差距并不明显。如果是出于性能方面的考虑,任选其一皆可。

如下是测试相关参数,配置及代码:

  • Fastjson:2.0.60
  • Jackson:2.20.1

添加如下依赖:

<!-- fastjson -->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.60</version>
</dependency><!-- jackson -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.20.1</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.datatype</groupId><artifactId>jackson-datatype-jsr310</artifactId><version>2.16.1</version><scope>compile</scope><exclusions><exclusion><artifactId>jackson-annotations</artifactId><groupId>com.fasterxml.jackson.core</groupId></exclusion><exclusion><artifactId>jackson-core</artifactId><groupId>com.fasterxml.jackson.core</groupId></exclusion><exclusion><artifactId>jackson-databind</artifactId><groupId>com.fasterxml.jackson.core</groupId></exclusion></exclusions>
</dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope>
</dependency>

用于测试的Java类:

/*** 用于序列化和反序列化测试的复杂对象*/
public class ComplexJsonObject {private Map<String, String> map;private List<Integer> list;private String str;private Integer i;private Long l;private Double d;private Float f;private Short s;private Byte b;private Character c;private Boolean bool;public Map<String, String> getMap() {return map;}public void setMap(Map<String, String> map) {this.map = map;}public List<Integer> getList() {return list;}public void setList(List<Integer> list) {this.list = list;}public String getStr() {return str;}public void setStr(String str) {this.str = str;}public Integer getI() {return i;}public void setI(Integer i) {this.i = i;}public Long getL() {return l;}public void setL(Long l) {this.l = l;}public Double getD() {return d;}public void setD(Double d) {this.d = d;}public Float getF() {return f;}public void setF(Float f) {this.f = f;}public Short getS() {return s;}public void setS(Short s) {this.s = s;}public Byte getB() {return b;}public void setB(Byte b) {this.b = b;}public Character getC() {return c;}public void setC(Character c) {this.c = c;}public Boolean getBool() {return bool;}public void setBool(Boolean bool) {this.bool = bool;}
}/*** 用于序列化和反序列化测试的简单对象*/
public class SimpleJsonObject {private String str;private Integer i;private Long l;private Double d;private Float f;private Short s;private Byte b;private Character c;private Boolean bool;public String getStr() {return str;}public void setStr(String str) {this.str = str;}public Integer getI() {return i;}public void setI(Integer i) {this.i = i;}public Long getL() {return l;}public void setL(Long l) {this.l = l;}public Double getD() {return d;}public void setD(Double d) {this.d = d;}public Float getF() {return f;}public void setF(Float f) {this.f = f;}public Short getS() {return s;}public void setS(Short s) {this.s = s;}public Byte getB() {return b;}public void setB(Byte b) {this.b = b;}public Character getC() {return c;}public void setC(Character c) {this.c = c;}public Boolean getBool() {return bool;}public void setBool(Boolean bool) {this.bool = bool;}
}/*** Fastjson工具*/
public final class FastjsonUtil {/*** 将对象序列化为JSON字符串* @param obj* @return*/public static String toJSON(Object obj) {return JSON.toJSONString(obj);}/*** 将JSON字符串反序列化为对象* @param json* @param clazz* @return* @param <T>*/public static <T> T fromJSON(String json, Class<T> clazz) {return JSON.parseObject(json, clazz);}
}/*** Jackson工具*/
public final class JacksonUtil {private static final ObjectMapper mapper;static {mapper = new ObjectMapper();mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);mapper.registerModule(new JavaTimeModule());mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));}/*** 将对象序列化为JSON字符串* @param obj* @return*/public static String toJSON(Object obj) {try {return mapper.writeValueAsString(obj);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 将JSON字符串反序列化为对象* @param json* @param clazz* @return* @param <T>*/public static <T> T fromJSON(String json, Class<T> clazz) {try {return mapper.readValue(json, clazz);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 格式化JSON字符串* @param json* @return*/public static String formatJSON(String json) {try {Object obj = mapper.readValue(json, Object.class);return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}
}/*** JSON序列化和反序列化测试*/
public class JsonUtilTest extends TestCase {private ComplexJsonObject complexJsonObject = new ComplexJsonObject();private SimpleJsonObject simpleJsonObject = new SimpleJsonObject();{init();}public void init () {Map<String, String> map = new HashMap<String, String>();for (int i = 0; i < 50000; i++) {map.put("key" + i, "value" + i);}List<Integer> list = new ArrayList<Integer>();for (int i = 0; i < 50000; i++) {list.add(i);}complexJsonObject.setMap(map);complexJsonObject.setList(list);complexJsonObject.setStr("This is complex json object string");complexJsonObject.setI(1);complexJsonObject.setL(100000000L);complexJsonObject.setD(1.0);complexJsonObject.setF(3.14f);complexJsonObject.setS((short) 10);complexJsonObject.setB(Byte.valueOf((byte) 1));complexJsonObject.setC(Character.valueOf('c'));complexJsonObject.setBool(true);simpleJsonObject.setStr("This is simple json object string");simpleJsonObject.setI(1);simpleJsonObject.setL(100000000L);simpleJsonObject.setD(1.0);simpleJsonObject.setF(3.14f);simpleJsonObject.setS((short) 10);simpleJsonObject.setB(Byte.valueOf((byte) 1));simpleJsonObject.setC(Character.valueOf('c'));simpleJsonObject.setBool(true);}/*** 测试FastjsonUtil工具*/public void testFastjsonUtilWithComplexObject() {long start = System.currentTimeMillis();String json = FastjsonUtil.toJSON(complexJsonObject);long end = System.currentTimeMillis();System.out.println("testFastjsonUtilWithComplexObject serialization took " + (end - start) + " ms");//System.out.println(json);start = System.currentTimeMillis();FastjsonUtil.fromJSON(json, ComplexJsonObject.class);end = System.currentTimeMillis();System.out.println("testFastjsonUtilWithComplexObject deserialization took " + (end - start) + " ms");}/*** 测试FastjsonUtil工具*/public void testFastjsonUtilWithSimpleObject() {long start = System.currentTimeMillis();String json = FastjsonUtil.toJSON(simpleJsonObject);long end = System.currentTimeMillis();System.out.println("testFastjsonUtilWithSimpleObject serialization took " + (end - start) + " ms");//System.out.println(json);start = System.currentTimeMillis();FastjsonUtil.fromJSON(json, SimpleJsonObject.class);end = System.currentTimeMillis();System.out.println("testFastjsonUtilWithSimpleObject deserialization took " + (end - start) + " ms");}/*** 测试JacksonUtil工具*/public void testJacksonUtilWithComplexObject() {long start = System.currentTimeMillis();String json = JacksonUtil.toJSON(complexJsonObject);long end = System.currentTimeMillis();System.out.println("testJacksonUtilWithComplexObject serialization took " + (end - start) + " ms");//System.out.println(json);start = System.currentTimeMillis();JacksonUtil.fromJSON(json, ComplexJsonObject.class);end = System.currentTimeMillis();System.out.println("testJacksonUtilWithComplexObject deserialization took " + (end - start) + " ms");}/*** 测试JacksonUtil工具*/public void testJacksonUtilWithSimpleObject() {long start = System.currentTimeMillis();String json = JacksonUtil.toJSON(simpleJsonObject);long end = System.currentTimeMillis();System.out.println("testJacksonUtilWithSimpleObject serialization took " + (end - start) + " ms");//System.out.println(json);start = System.currentTimeMillis();JacksonUtil.fromJSON(json, SimpleJsonObject.class);end = System.currentTimeMillis();System.out.println("testJacksonUtilWithSimpleObject deserialization took " + (end - start) + " ms");}
}

但是如果考虑流行度,文档全面性,兼容性,特性支持,BUG监测等方面,就需要慎重选择了。

比如:Spring全家桶默认使用的JSON库是Jackson,考虑到兼容性可能需要优先考虑使用它。如果在序列化和反序列化时还需要考虑某些特性支持,还需要专门测试验证后进行敲定。

【参考】
深度对比Jackson和Fastjson,最终我还是选择了
Spring Boot Jackson 和Fast JSON 用哪个好啊

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

解决Spring Cloud Gateway中使用CompletableFuture.supplyAsync()执行Feign调用报错

报错背景描述 组件版本信息:Spring Cloud:2021.0.5 Spring Cloud Alibaba:2021.0.5.0 Nacos:2.2.3项目采用基于Spring Cloud Alibaba + Nacos的微服务架构,生产环境部署时服务部署到阿里云ACK容器集群中,并使用阿…

补发读后感2

《代码大全》作为软件开发领域的经典著作,不仅是技术手册,更是程序员的思维指南。通读后,我深刻体会到“编写可维护的代码”远比“实现功能”更为重要。 书中对代码规范的细致讲解让我受益匪浅。从前我编写代码时只…

解决mybatis批量更新慢问题

批量更新的实现方式 在数据库上执行批量更新无非2种方式: 其一,在应用层通过循环的方式多次执行单条UPDATE语句,使用该方式性能最差,每次执行UPDATE操作都需要经历"建立连接 -> 执行SQL语句 -> 释放链接…

qy_蓝桥杯编程系列_编程18 进制转换

编程18 进制转换这题初看有点复杂,但只要理解进制转换的原理,加上一点字符串运用方法,就可以很顺畅的解决啦一、题目简介如图所示为本题要求,需要将一个N进制的数S转换成M进制,一共T个测试数据。 二、重点解析 2…

详细介绍:kotlin - 显示HDR图(heic格式),使用GainMap算法,速度从5秒提升到0.6秒

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

anything

ValueError Traceback (most recent call last)Cell In[20], line 8 3 client = OpenAI() 4 # client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_BASE_URL…

递归函数,闭包,装饰器3

递归函数,闭包,装饰器3递归函数 含义:如果一个函数在内部不调用其他的函数,而是调用它本身的话,这个函数就是递归函数 条件: 1,明确的结束条件 2.没进行更深一层的递归时,问题规模相比上次递归都要有所减少。…

从vw/vh到clamp(),前端响应式设计的痛点与进化 - 实践

从vw/vh到clamp(),前端响应式设计的痛点与进化 - 实践2025-12-03 20:17 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; d…

10413_基于Springboot的智慧养老院管理系统

1、项目包含 项目源码、项目文档、数据库脚本、软件工具等资料; 带你从零开始部署运行本套系统。 2、项目介绍 随着老龄化社会的加速发展,传统养老院管理模式面临效率低、服务滞后等挑战。本研究着力打造一套凭Sprin…

【Unity URP】Rendering Debugger和可视化MipMap方案

写在前面 最近开始学习Unity性能优化,是结合了《Unity游戏优化》这本书和教程《Unity性能优化》第叁节——静态资源优化(3)——纹理的基础概念一起学习。在学习纹理优化部分时候遇到了问题,固定管线下Unity的Scene窗…

How to do a biology experiment for a Physician.

Im not kidding.Be early. Normally, all materials should be scheduled. But if theres not schedule, all biologists will think he is important ———— because they know what life is. The humblest will be…

2025–2030 年最紧缺的八大 IC 岗位

面对摩尔定律放缓、AI 和汽车电子爆发、Chiplet 与 3D-IC 持续改写系统架构,半导体行业正在进入一个全新的竞争周期。技术路径的变化,也正在深刻影响人才需求结构:行业不再只需要“通才”,而是更稀缺、也更关键的专…

Firefox 禁用按下 Alt 显示菜单

进入 about:config,将 ui.key.menuAccessKey 默认的 18 改成 0,重启浏览器。

LC 3479(2100) 线段树二分 水果成篮

题目 题目: 给你两个长度为 n 的整数数组,fruits 和 baskets,其中 fruits[i] 表示第 i 种水果的 数量,baskets[j] 表示第 j 个篮子的 容量。 你需要对 fruits 数组从左到右按照以下规则放置水果: 每种水果必须放入…

文件的常用操作

Path相关操作,主要为文件属性,路径目录等点击查看代码 def _Path():from pathlib import Pathimport shutil# 创建 Path 对象print(Path().absolute())p = Path("data/example.txt")p1 = Path("data/d…

聊聊Oracle数据库的向量能力 - 详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

ReAct+LangGraph:构建智能AI Agent的完整指南(建议收藏) - 详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

第七天项目

苍穹外卖项目 - 第7天冲刺日志(项目总结与复盘) 日期:2025-12-02 冲刺周期:第7天/共7天 参会人员:李靖华 温尚熙 谢斯越 郑哲磊一、站立会议照片团队成员进行项目总结和复盘讨论二、最终验收会议记录 郑哲磊(后端…

Spring Boot框架中在Controller方法里获取Request和Response对象的2种方式

写在前面 javax.servlet.ServletRequest和javax.servlet.ServletResponse都是Servlet容器中定义的接口,分别用于获取客户端请求信息和将响应消息发送给客户端。 有两种方法在Contoller方法中获取它们:直接在Controll…

2025煤炭氟氯测定仪TOP5权威推荐:精准检测选对品牌,奥

煤质环保检测领域中,氟氯测定仪作为判定煤炭环保合规性的核心设备,其精准度、耐用性直接影响检测结果与企业生产效率。2024年行业数据显示,因氟氯测定仪检测偏差导致的环保合规风险事件占煤质检测问题的30%,而耐用…