比较 JSON API Gson 和 Jackson

一则或许对你有用的小广告

欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论

  • 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于 Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...点击查看项目介绍 ;
  • 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;

截止目前, 星球 内专栏累计输出 63w+ 字,讲解图 2808+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2200+ 小伙伴加入学习 ,欢迎点击围观

在这篇文章中,我们将从性能的角度比较两个著名的 JSON 特定 API,即 Gson 和 Jackson:

代码

包装纸

此类用于转换为 JSON


 public class MeasurementRecord {

private String measurementId;

private long duration;

private long time;

private MeasurementType type=MeasurementType.METHOD_CALL;

/** *

  • @param measurementId
  • @param duration
  • @param time
  • @param type */ public MeasurementRecord(String measurementId, long duration, long time, MeasurementType type) { super(); this.measurementId = measurementId; this.duration = duration; this.time = time; this.type = type; } //getters and setters }

public enum MeasurementType {

WEB_REQUEST,SQL,EXCEPTION,METHOD_CALL

}

创建列表的代码


 public class MeasurementRecord {

private String measurementId;

private long duration;

private long time;

private MeasurementType type=MeasurementType.METHOD_CALL;

/** *

  • @param measurementId
  • @param duration
  • @param time
  • @param type */ public MeasurementRecord(String measurementId, long duration, long time, MeasurementType type) { super(); this.measurementId = measurementId; this.duration = duration; this.time = time; this.type = type; } //getters and setters }

public enum MeasurementType {

WEB_REQUEST,SQL,EXCEPTION,METHOD_CALL

}

杰克逊API


 public class MeasurementRecord {

private String measurementId;

private long duration;

private long time;

private MeasurementType type=MeasurementType.METHOD_CALL;

/** *

  • @param measurementId
  • @param duration
  • @param time
  • @param type */ public MeasurementRecord(String measurementId, long duration, long time, MeasurementType type) { super(); this.measurementId = measurementId; this.duration = duration; this.time = time; this.type = type; } //getters and setters }

public enum MeasurementType {

WEB_REQUEST,SQL,EXCEPTION,METHOD_CALL

}

开发者接口


 public class MeasurementRecord {

private String measurementId;

private long duration;

private long time;

private MeasurementType type=MeasurementType.METHOD_CALL;

/** *

  • @param measurementId
  • @param duration
  • @param time
  • @param type */ public MeasurementRecord(String measurementId, long duration, long time, MeasurementType type) { super(); this.measurementId = measurementId; this.duration = duration; this.time = time; this.type = type; } //getters and setters }

public enum MeasurementType {

WEB_REQUEST,SQL,EXCEPTION,METHOD_CALL

}

结果

结论

对于中小型列表的转换,与 Jackson 相比,Gson 提供了更好的响应。对于大型列表,Jackson 提供了比 Gson 更好的响应。基于这一结果,我们可以得出结论,为了将中小型列表转换为 JSON,可以使用 Gson 以获得更好的性能。

相关文章