FastJson 和 Gson 都是 Java 中用于处理 JSON 字符串和对象之间转换的库。

FastJson 的优点是轻量级,速度快,支持泛型和注解。

Gson 的优点是功能强大,精确度高,无依赖,支持复杂类型的转换。

使用 FastJson

FastJson 是阿里巴巴团队发布的,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。

fastjson 虽然效率高,但如果没有仔细通读说明文档而直接使用的话,容易踩入一些坑中:

  • 被序列化/反序列化的类,每一个属性都需要带getter/setter.并且不能在方法体内写特殊的逻辑。按照标准生成public的getter、setter,严禁添加其他带get、set开头的public方法

  • fastjson会反射获取类的构造函数,如果没有无参构造函数,就可能会调用其他构造函数,相当于自动为对象进行初始化,造成数据混乱现象,解决方法为:添加一个无参空构造函数

要使用 FastJson,你需要在 Maven 项目中添加 FastJson 依赖。

1
2
3
4
5
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>

代码:

1
2
3
4
5
6
7
8
9
import com.alibaba.fastjson.JSON;

// 使用 FastJson 将 Person 对象转换为 JSON 字符串
String jsonStr1 = JSON.toJSONString(person);
System.out.println("使用 FastJson 转换后的结果:" + jsonStr1);

// 使用 FastJson 将 JSON 字符串转换为 Person 对象
Person person1 = JSON.parseObject(jsonStr1, Person.class);
System.out.println("使用 FastJson 转换后的对象:" + person1.getName() + ", " + person1.getAge());

使用 Gson

GSON 是一个开源的 Java 库,可以将 Java 对象转换为 JSON 格式,也可以将 JSON 字符串转换为 Java 对象。

要使用 GSON,你需要在 Maven 项目中添加 GSON 依赖。

1
2
3
4
5
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>

代码:

1
2
3
4
5
6
7
8
9
10
11
import com.google.gson.Gson;

// 创建一个 Gson 对象
Gson gson = new Gson();
// 使用 Gson 将 Person 对象转换为 JSON 字符串
String jsonStr2 = gson.toJson(person);
System.out.println("使用 Gson 转换后的结果:" + jsonStr2);

// 使用 Gson 将 JSON 字符串转换为 Person 对象
Person person2 = gson.fromJson(jsonStr2, Person.class);
System.out.println("使用 Gson 转换后的对象:" + person2.getName() + ", " + person2.getAge());

准备

新建一个被测试的对象类 TestObj 和 propertyClass。

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
// TestObj

import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.Map;

/* fastJson ,必须保证对象的属性都有 Getter 和 Setter */
@Getter
@Setter
public class TestObj {
int propertyInt;
String propertyString;
List<String> propertyList;
Map<String, List<Integer>> propertyMap;
PropertyClass propertyClass;

/* fastJson 使用 parseObject 函数时,必须保证对象有无参构造方法 */
public TestObj(){}
public TestObj(int pi, String ps) {
this.propertyInt = pi;
this.propertyString = ps;
}
public TestObj(int pi, String ps, List<String> pl, Map<String, List<Integer>> pm, PropertyClass pc) {
this(pi, ps);
this.propertyList = pl;
this.propertyMap = pm;
this.propertyClass = pc;
}
}

// PropertyClass
import lombok.Getter;
import lombok.Setter;

import java.util.Map;

/* fastJson ,必须保证对象的属性都有 Getter 和 Setter */
@Getter
@Setter
public class PropertyClass {
double subDouble;
String subStr;
Map<Integer, String> subMap;

/* fastJson 使用 parseObject 函数时,必须保证对象有无参构造方法 */
public PropertyClass() {}

public PropertyClass(double subDouble, String subStr, Map<Integer, String> subMap) {
this.subDouble = subDouble;
this.subStr = subStr;
this.subMap = subMap;
}
}

测试

使用 Main 对 Gson 和 FastJson 进行测试。

如下代码的解释:

FastJson 测试

  • 首先新建一个 TestObj 类的对象,
  • 然后使用 FastJson 存储到文件 output/fastjson.json 中,
  • 使用 FastJson 读取 output/gson.json,并将得到的 TestObj 类对象存储到 output/fastjsonRead.json 中

Gson 测试

  • 首先新建一个 TestObj 类的对象,
  • 然后使用 Gson 存储到文件 output/gson.json 中,
  • 使用 Gson 读取 output/gson.json,并将得到的 TestObj 类对象存储到 output/gsonRead.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
public static void main(String[] args) {
Main main = new Main();
// 测试 Gson
System.out.println("Test Gson");
main.testGsonWrite();
main.testGsonRead();

// 测试 FastJson
System.out.println("Test FastJson");
main.testFastJsonWrite();
main.testFastJsonRead();
}

// -- 测试 FastJson ---
public void testFastJsonWrite() {
TestObj testObj = getTestObj();

// Convert the object to JSON string
String jsonString = JSON.toJSONString(testObj);

try {
// Write the JSON string to a file
FileWriter writer = new FileWriter("output/fastjson.json");
writer.write(jsonString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void testFastJsonRead() {
// Convert the JSON string back to object
String jsonString = "";
// 从文件中读取JSON字符串
FileReader fileReader = null;
try {
fileReader = new FileReader("output/fastjson.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
jsonString = bufferedReader.readLine();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}

// Convert the JSON String to object
TestObj testObj = JSON.parseObject(jsonString, TestObj.class);
testReadObj(testObj);

// Read the fastjsonRead.json using BufferedReader
try {
FileWriter writer = new FileWriter("output/fastjsonRead.json");
writer.write(jsonString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

// -- 测试 Gson ---
public void testGsonWrite() {
TestObj testObj = getTestObj();

// Create a Gson object
Gson gson = new Gson();
try {
// Write the JSON string to a file
FileWriter writer = new FileWriter("output/gson.json");
gson.toJson(testObj, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public void testGsonRead() {
// 使用对象模型,将 JSON 字符串或文件转换为 Java 对象或集合12。
// 这种方法需要你提前定义好与 JSON 结构对应的 Java 类,
// 然后使用 Gson 的 fromJson 方法来进行转换。
// Create a new Gson object
Gson gson = new Gson();

// Read the gson.json using BufferedReader
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("output/gson.json"));

// Convert the JSON String to object
TestObj testObj = gson.fromJson(br, TestObj.class);

testReadObj(testObj);

FileWriter writer = new FileWriter("output/gsonRead.json");
gson.toJson(testObj, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// -- 工具方法 ---
private TestObj getTestObj() {
// 构建 TestObj 对象
int propertyInt = 1;
String propertyString = "gj1";
List<String> propertyList = List.of("gjitem1", "gjitem2", "gjitem3");

Map<String, List<Integer>> propertyMap = new HashMap<>();
List<Integer> mapitem1 = List.of(1,2,3);
List<Integer> mapitem2 = List.of(3,2,1);
propertyMap.put("233", mapitem1);
propertyMap.put("234", mapitem2);

Map<Integer, String> subMap = new HashMap<>();
subMap.put(0, "好好学习");
subMap.put(1, "天天向上");
PropertyClass propertyClass = new PropertyClass(2.33, "substring", subMap);

TestObj testObj = new TestObj(propertyInt, propertyString, propertyList, propertyMap, propertyClass);
return testObj;
}

private void testReadObj(TestObj testObj) {
System.out.println(testObj.propertyInt == 1);
System.out.println(testObj.propertyList.get(0).equals("gjitem1"));
System.out.println(testObj.propertyClass.subStr.equals("substring"));
System.out.println(testObj.propertyClass.subMap.get(0).equals("好好学习"));
}
}

得到的 output/gson.jsonoutput/gsonRead.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
{
"propertyInt":1,
"propertyString":"gj1",
"propertyList":[
"gjitem1",
"gjitem2",
"gjitem3"
],
"propertyMap":{
"233":[
1,
2,
3
],
"234":[
3,
2,
1
]
},
"propertyClass":{
"subDouble":2.33,
"subStr":"substring",
"subMap":{
"0":"好好学习",
"1":"天天向上"
}
}
}

得到的 output/fastjson.jsonoutput/fastjsonRead.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
{
"propertyClass":{
"subDouble":2.33,
"subMap":{
0:"好好学习",
1:"天天向上"
},
"subStr":"substring"
},
"propertyInt":1,
"propertyList":[
"gjitem1",
"gjitem2",
"gjitem3"
],
"propertyMap":{
"233":[
1,
2,
3
],
"234":[
3,
2,
1
]
},
"propertyString":"gj1"
}

测试结果:

1
2
3
4
5
6
7
8
9
10
Test Gson
true
true
true
true
Test FastJson
true
true
true
true

测试成功!

参考

待阅读文章