Java幾種常用JSON庫性能比較


JSON不管是在Web開發還是服務器開發中是相當常見的數據傳輸格式,一般情況我們對於JSON解析構造的性能並不需要過於關心,除非是在性能要求比較高的系統。

目前對於Java開源的JSON類庫有很多種,下面我們取4個常用的JSON庫進行性能測試對比, 同時根據測試結果分析如果根據實際應用場景選擇最合適的JSON庫。

這4個JSON類庫分別為:Gson,FastJson,Jackson,Json-lib。

簡單介紹

選擇一個合適的JSON庫要從多個方面進行考慮:

  1. 字符串解析成JSON性能
  2. 字符串解析成JavaBean性能
  3. JavaBean構造JSON性能
  4. 集合構造JSON性能
  5. 易用性

先簡單介紹下四個類庫的身份背景

Gson

項目地址:https://github.com/google/gson

Gson是目前功能最全的Json解析神器,Gson當初是為因應Google公司內部需求而由Google自行研發而來,但自從在2008年五月公開發布第一版后已被許多公司或用戶應用。 Gson的應用主要為toJson與fromJson兩個轉換函數,無依賴,不需要例外額外的jar,能夠直接跑在JDK上。 在使用這種對象轉換之前,需先創建好對象的類型以及其成員才能成功的將JSON字符串成功轉換成相對應的對象。 類里面只要有get和set方法,Gson完全可以實現復雜類型的json到bean或bean到json的轉換,是JSON解析的神器。

FastJson

項目地址:https://github.com/alibaba/fastjson

Fastjson是一個Java語言編寫的高性能的JSON處理器,由阿里巴巴公司開發。無依賴,不需要例外額外的jar,能夠直接跑在JDK上。 FastJson在復雜類型的Bean轉換Json上會出現一些問題,可能會出現引用的類型,導致Json轉換出錯,需要制定引用。 FastJson采用獨創的算法,將parse的速度提升到極致,超過所有json庫。

Jackson

項目地址:https://github.com/FasterXML/jackson

Jackson是當前用的比較廣泛的,用來序列化和反序列化json的Java開源框架。Jackson社區相對比較活躍,更新速度也比較快, 從Github中的統計來看,Jackson是最流行的json解析器之一,Spring MVC的默認json解析器便是Jackson。

Jackson優點很多:

  1. Jackson 所依賴的jar包較少,簡單易用。
  2. 與其他 Java 的 json 的框架 Gson 等相比,Jackson 解析大的 json 文件速度比較快。
  3. Jackson 運行時占用內存比較低,性能比較好
  4. Jackson 有靈活的 API,可以很容易進行擴展和定制。

目前最新版本是2.9.4,Jackson 的核心模塊由三部分組成:

  1. jackson-core 核心包,提供基於”流模式”解析的相關 API,它包括 JsonPaser 和 JsonGenerator。Jackson 內部實現正是通過高性能的流模式 API 的 JsonGenerator 和 JsonParser 來生成和解析 json。
  2. jackson-annotations 注解包,提供標准注解功能;
  3. jackson-databind 數據綁定包,提供基於”對象綁定” 解析的相關 API( ObjectMapper )和”樹模型” 解析的相關 API(JsonNode);基於”對象綁定” 解析的 API 和”樹模型”解析的 API 依賴基於”流模式”解析的 API。

為什么Jackson的介紹這么長啊?因為它也是本人的最愛。

Json-lib

項目地址:http://json-lib.sourceforge.net/index.html

json-lib最開始的也是應用最廣泛的json解析工具,json-lib 不好的地方確實是依賴於很多第三方包,對於復雜類型的轉換,json-lib對於json轉換成bean還有缺陷, 比如一個類里面會出現另一個類的list或者map集合,json-lib從json到bean的轉換就會出現問題。json-lib在功能和性能上面都不能滿足現在互聯網化的需求。

編寫性能測試

接下來開始編寫這四個庫的性能測試代碼。

添加maven依賴

當然首先是添加四個庫的maven依賴,公平起見,我全部使用它們最新的版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!-- Json libs-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>

四個庫的工具類

FastJsonUtil.java

1
2
3
4
5
6
7
8
9
public class FastJsonUtil {
public static String bean2Json(Object obj) {
return JSON.toJSONString(obj);
}

public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
return JSON.parseObject(jsonStr, objClass);
}
}

GsonUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class GsonUtil {
private static Gson gson = new GsonBuilder().create();

public static String bean2Json(Object obj) {
return gson.toJson(obj);
}

public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
return gson.fromJson(jsonStr, objClass);
}

public static String jsonFormatter(String uglyJsonStr) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJsonStr);
return gson.toJson(je);
}
}

JacksonUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();

public static String bean2Json(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}

public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
try {
return mapper.readValue(jsonStr, objClass);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

JsonLibUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
public class JsonLibUtil {

public static String bean2Json(Object obj) {
JSONObject jsonObject = JSONObject.fromObject(obj);
return jsonObject.toString();
}

@SuppressWarnings("unchecked")
public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
return (T) JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass);
}
}

准備Model類

這里我寫一個簡單的Person類,同時屬性有Date、List、Map和自定義的類FullName,最大程度模擬真實場景。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Person {
private String name;
private FullName fullName;
private int age;
private Date birthday;
private List<String> hobbies;
private Map<String, String> clothes;
private List<Person> friends;

// getter/setter省略

@Override
public String toString() {
StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age="
+ age + ", birthday=" + birthday + ", hobbies=" + hobbies
+ ", clothes=" + clothes + "]\n");
if (friends != null) {
str.append("Friends:\n");
for (Person f : friends) {
str.append("\t").append(f);
}
}
return str.toString();
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class FullName {
private String firstName;
private String middleName;
private String lastName;

public FullName() {
}

public FullName(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}

// 省略getter和setter

@Override
public String toString() {
return "[firstName=" + firstName + ", middleName="
+ middleName + ", lastName=" + lastName + "]";
}
}

JSON序列化性能基准測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonSerializeBenchmark {
/**
* 序列化次數參數
*/
@Param({"1000", "10000", "100000"})
private int count;

private Person p;

public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(JsonSerializeBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(0)
.build();
Collection<RunResult> results = new Runner(opt).run();
ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");
}

@Benchmark
public void JsonLib() {
for (int i = 0; i < count; i++) {
JsonLibUtil.bean2Json(p);
}
}

@Benchmark
public void Gson() {
for (int i = 0; i < count; i++) {
GsonUtil.bean2Json(p);
}
}

@Benchmark
public void FastJson() {
for (int i = 0; i < count; i++) {
FastJsonUtil.bean2Json(p);
}
}

@Benchmark
public void Jackson() {
for (int i = 0; i < count; i++) {
JacksonUtil.bean2Json(p);
}
}

@Setup
public void prepare() {
List<Person> friends=new ArrayList<Person>();
friends.add(createAPerson("小明",null));
friends.add(createAPerson("Tony",null));
friends.add(createAPerson("陳小二",null));
p=createAPerson("邵同學",friends);
}

@TearDown
public void shutdown() {
}

private Person createAPerson(String name,List<Person> friends) {
Person newPerson=new Person();
newPerson.setName(name);
newPerson.setFullName(new FullName("zjj_first", "zjj_middle", "zjj_last"));
newPerson.setAge(24);
List<String> hobbies=new ArrayList<String>();
hobbies.add("籃球");
hobbies.add("游泳");
hobbies.add("coding");
newPerson.setHobbies(hobbies);
Map<String,String> clothes=new HashMap<String, String>();
clothes.put("coat", "Nike");
clothes.put("trousers", "adidas");
clothes.put("shoes", "安踏");
newPerson.setClothes(clothes);
newPerson.setFriends(friends);
return newPerson;
}
}

說明一下,上面的代碼中

1
ResultExporter.exportResult("JSON序列化性能", results, "count", "秒");

這個是我自己編寫的將性能測試報告數據填充至Echarts圖,然后導出png圖片的方法,具體代碼我就不貼了,參考我的github源碼。

執行后的結果圖:

從上面的測試結果可以看出,序列化次數比較小的時候,Gson性能最好,當不斷增加的時候到了100000,Gson明細弱於Jackson和FastJson, 這時候FastJson性能是真的牛,另外還可以看到不管數量少還是多,Jackson一直表現優異。而那個Json-lib簡直就是來搞笑的。^_^

JSON反序列化性能基准測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@BenchmarkMode(Mode.SingleShotTime)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class JsonDeserializeBenchmark {
/**
* 反序列化次數參數
*/
@Param({"1000", "10000", "100000"})
private int count;

private String jsonStr;

public static void main(String[] args) throws Exception {
Options opt = new OptionsBuilder()
.include(JsonDeserializeBenchmark.class.getSimpleName())
.forks(1)
.warmupIterations(0)
.build();
Collection<RunResult> results = new Runner(opt).run();
ResultExporter.exportResult("JSON反序列化性能", results, "count", "秒");
}

@Benchmark
public void JsonLib() {
for (int i = 0; i < count; i++) {
JsonLibUtil.json2Bean(jsonStr, Person.class);
}
}

@Benchmark
public void Gson() {
for (int i = 0; i < count; i++) {
GsonUtil.json2Bean(jsonStr, Person.class);
}
}

@Benchmark
public void FastJson() {
for (int i = 0; i < count; i++) {
FastJsonUtil.json2Bean(jsonStr, Person.class);
}
}

@Benchmark
public void Jackson() {
for (int i = 0; i < count; i++) {
JacksonUtil.json2Bean(jsonStr, Person.class);
}
}

@Setup
public void prepare() {
jsonStr="{\"name\":\"邵同學\",\"fullName\":{\"firstName\":\"zjj_first\",\"middleName\":\"zjj_middle\",\"lastName\":\"zjj_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":[{\"name\":\"小明\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"Tony\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null},{\"name\":\"陳小二\",\"fullName\":{\"firstName\":\"xxx_first\",\"middleName\":\"xxx_middle\",\"lastName\":\"xxx_last\"},\"age\":24,\"birthday\":null,\"hobbies\":[\"籃球\",\"游泳\",\"coding\"],\"clothes\":{\"shoes\":\"安踏\",\"trousers\":\"adidas\",\"coat\":\"Nike\"},\"friends\":null}]}";
}

@TearDown
public void shutdown() {
}
}

執行后的結果圖:

從上面的測試結果可以看出,反序列化的時候,Gson、Jackson和FastJson區別不大,性能都很優異,而那個Json-lib還是來繼續搞笑的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM