1. Overview
1.概述
Gson is a Java library that allows us to convert Java Objects into a JSON representation. We can also use it the other way around, to convert a JSON string to an equivalent Java object.
Gson是一个Java库,它允许我们将Java对象转换成JSON表示。我们也可以反过来使用它,将JSON字符串转换为同等的Java对象。
In this quick tutorial, we’ll find out how to save various Java data types as a JSON in a file.
在这个快速教程中,我们将了解如何将各种Java数据类型保存为文件中的JSON。
2. Maven Dependencies
2.Maven的依赖性
First of all, we need to add the Gson dependency in pom.xml. This is available in Maven Central:
首先,我们需要在pom.xml中添加Gson依赖项。这可以在Maven Central中找到。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
3. Saving Data to a JSON File
3.将数据保存到JSON文件
We’ll use the toJson(Object src, Appendable writer) method from the Gson class to convert a Java data type into JSON and store it in a file. The Gson() constructor creates a Gson object with default configuration:
我们将使用toJson(Object src, Appendable writer) 方法,该方法来自Gson类,以将Java数据类型转换成JSON并存储在文件中。Gson()构造函数创建一个具有默认配置的Gson对象。
Gson gson = new Gson();
Now, we can call toJson() to convert and store Java objects.
现在,我们可以调用toJson()来转换和存储Java对象。
Let’s explore some examples with different data types in Java.
让我们来探讨一些Java中不同数据类型的例子。
3.1. Primitives
3.1.基元
Saving primitives to a JSON file is pretty straight-forward using GSON:
使用GSON将基元保存到JSON文件是非常直接的。
gson.toJson(123.45, new FileWriter(filePath));
Here, filePath denotes the location of the file. The file output will simply contain the primitive value:
这里,filePath表示文件的位置。文件输出将简单地包含原始值。
123.45
3.2. Custom Objects
3.2.自定义对象
Likewise, we can store objects as JSON.
同样,我们也可以将对象存储为JSON。
First, we’ll create a simple User class:
首先,我们将创建一个简单的User类。
public class User {
private int id;
private String name;
private transient String nationality;
public User(int id, String name, String nationality) {
this.id = id;
this.name = name;
this.nationality = nationality;
}
public User(int id, String name) {
this(id, name, null);
}
}
Now, we’ll store a User object as a JSON:
现在,我们将把一个User对象存储为JSON。
User user = new User(1, "Tom Smith", "American");
gson.toJson(user, new FileWriter(filePath));
The file output will be:
文件的输出将是。
{"id":1,"name":"Tom"}
If a field is marked transient, it’s ignored by default and not included in the JSON serialization or deserialization. As a result, the nationality field isn’t present in the JSON output.
如果一个字段被标记为transient,它将被默认忽略,并且不包括在JSON序列化或反序列化中。因此,国籍字段不会出现在JSON输出中。
Also by default, Gson omits null fields during serialization. So if we consider this example:
另外,默认情况下,Gson在序列化过程中会省略空字段。因此,如果我们考虑这个例子。
gson.toJson(new User(1, null, "Unknown"), new FileWriter(filePath));
the file output will be:
文件的输出将是。
{"id":1}
We’ll see how to include null fields in serialization later.
我们将在后面看到如何在序列化中包含空字段。
3.3. Collections
3.3.收藏
We can store a collection of objects in a similar manner:
我们可以用类似的方式来存储一个对象的集合。
User[] users = new User[] { new User(1, "Mike"), new User(2, "Tom") };
gson.toJson(users, new FileWriter(filePath));
In this case, the file output will be an array of User objects:
在这种情况下,文件输出将是一个User对象的数组。
[{"id":1,"name":"Mike"},{"id":2,"name":"Tom"}]
4. Using GsonBuilder
4.使用GsonBuilder
In order to tweak the default Gson configuration settings, we can utilize the GsonBuilder class.
为了调整默认的Gson配置设置,我们可以利用GsonBuilder类。
This class follows the builder pattern, and it’s typically used by first invoking various configuration methods to set desired options, and finally calling the create() method:
这个类遵循构建器模式,它的典型用法是首先调用各种配置方法来设置所需的选项,最后调用create()方法。
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
Here, we’re setting the pretty print option which is by default set to false. Similarly, to include null values in serialization, we can call serializeNulls(). The available options are listed here.
这里,我们要设置漂亮的打印选项,该选项默认设置为false。同样地,为了在序列化中包含空值,我们可以调用serializeNulls()。可用的选项被列在这里。
5. Conclusion
5.结论
In this quick article, we got an understanding of how to serialize various Java data types into a JSON file. To explore various articles on JSON, have a look at our other tutorials on this topic.
在这篇快速文章中,我们了解了如何将各种Java数据类型序列化为JSON文件。要探索关于JSON的各种文章,请看我们关于这个主题的其他教程。
As always, the code snippets are available in this GitHub repository.
一如既往,代码片段可在这个GitHub资源库中找到。