Gson – 快速指南

Gson – 快速指南

原文: https://howtodoinjava.com/gson/google-gson-tutorial/

Gson(由 Google 提供)是可用于将 Java 对象转换为 JSON 字符串的 Java 库。 此外,它还可以用于将 JSON 字符串转换为等效的 Java 对象

还有其他一些 Java 库也可以执行此转换,但是 Gson 处于极少数情况,不需要任何预先注解的 Java 类或 Java 类的源代码。

Gson 还支持旧的 Java 类,这些类中不支持泛型来提供类型信息。 它只是与这些旧式类一起正常工作。

在这个 gson 教程中,我仅给出一些示例,这些示例可以用 Gson 执行。

Table of Contents

1\. Prerequisites and dependency
2\. Create Gson object
3\. Convert Java objects to JSON format
4\. Convert JSON to Java Objects
5\. Writing an Instance Creator
6\. Custom Serialization and De-serialization
7\. Pretty Printing for JSON Output Format
8\. Versioning Support
9\. More Gson Tutorials

1.先决条件和依赖项

1.1 POJO 类

在介绍示例之前,让我们先准备一个 POJO 类,该类将在给定的示例中使用。

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;

   public Employee(){      
   }

   public Employee(Integer id, String firstName, String lastName, Date birthDate){
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
   }

   //Getters and setters

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

1.2 Maven 依赖

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

在 gradle 中,请使用以下依赖项。

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

2.创建 Gson 对象

Gson 对象可以通过两种方式创建。 第一种方法为您准备了快速的 Gson 对象,可以进行更快的编码,而第二种方法使用GsonBuilder来构建更复杂的 Gson 对象。

//1\. Default constructor
Gson gson = new Gson();

//2\. Using GsonBuilder
Gson gson = new GsonBuilder()
			 .disableHtmlEscaping()
			 .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
			 .setPrettyPrinting()
			 .serializeNulls()
			 .create();

使用GsonBuilder时,可以为Gson对象提供许多其他有用选项。 继续检查一下。

3. Gson toJson() – 将 Java 对象转换为 JSON 字符串

要将将对象转换为 json,请使用toJson()方法。

Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));

Gson gson = new Gson();

System.out.println(gson.toJson(employee));

程序输出。

{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}

4. 3. Gson fromJson() – 将 JSON 字符串转换为对象

将 json 解析为对象,请使用 fromJson() 方法。

Gson gson = new Gson();

System.out.println(
	gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER']}", 
	Employee.class));

程序输出:

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER]]

5. Gson InstanceCreator– 给定对象中不存在无参构造器时

在大多数情况下,即使任何类都不提供默认的无参数构造器, Gson 库也足以创建实例。 但是,如果使用无参数构造器的类发现任何问题,则可以使用InstanceCreator支持。 使用它之前,您需要先向 Gson 注册 Java 类类型的InstanceCreator

例如,Department没有任何默认构造器。

public class Department
{
   public Department(String deptName)
   {
      this.deptName = deptName;
   }

   private String deptName;

   public String getDeptName()
   {
      return deptName;
   }

   public void setDeptName(String deptName)
   {
      this.deptName = deptName;
   }

   @Override
   public String toString()
   {
      return "Department [deptName="+deptName+"]";
   }
}

我们的Employee类引用了Department

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
   private Department department; //Department reference

   //Other setters and getters
}

要正确使用Department类,我们需要为Department注册一个InstanceCreator,如下所示:

class DepartmentInstanceCreator implements InstanceCreator<Department> {
   public Department createInstance(Type type)
   {
      return new Department("None");
   }
}

现在,如下使用上述InstanceCreator

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());

Gson gson = gsonBuilder.create();

System.out.println(
            gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta',
            'roles':['ADMIN','MANAGER'],'department':{'deptName':'Finance'}}", 
            Employee.class));

程序输出:

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]

6. Gson 自定义序列化和反序列化

很多时候,我们需要写入/读取不是 Java 对象默认表示形式的 JSON 值。 在这种情况下,我们需要编写该 Java 类型的自定义序列化器和反序列化器。

在我们的示例中,我正在为java.util.Date类编写序列化器和反序列化器,这将有助于以“dd/MM/yyyy”格式编写日期格式。

6.1 Gson 自定义序列化器

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class DateSerializer implements JsonSerializer<Date>
{
   private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context)
   {
      return new JsonPrimitive(dateFormat.format(date));
   }
}

6.2 Gson 自定义反序列化器

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;

public class DateDeserializer implements JsonDeserializer<Date>
{
   private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
   public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context)
   {
      try
      {
         return dateFormat.parse(dateStr.getAsString());
      } 
      catch (ParseException e)
      {
         e.printStackTrace();
      }
      return null;
   }
}

6.3 注册自定义序列化器和反序列化器

现在,您可以在GsonBuilder中注册这些串行器和反序列化器,如下所示:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

6.4 Gson 自定义序列化器和反序列化器示例

串行器和反序列化器的完整示例如下。

Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
employee.setBirthDate(new Date());

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());
Gson gson = gsonBuilder.create();

//Convert to JSON
System.out.println(gson.toJson(employee));

//Convert to java objects
System.out.println(gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta',
                                 'roles':['ADMIN','MANAGER'],'birthDate':'17/06/2014'}"
							           , Employee.class));

程序输出:

{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"],"birthDate":"17/06/2014"}

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], birthDate=Tue Jun 17 00:00:00 IST 2014]	

7. Gson setPrettyPrinting() – 精美打印 JSON 输出

Gson 提供的默认 JSON 输出是紧凑的 JSON 格式。 这意味着在输出 JSON 结构中将没有任何空格。 要生成更具可读性和美观的 JSON,请使用GsonBuilder中的 setPrettyPrinting()

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(employee);

程序输出:

{
  "id": 1,
  "firstName": "Lokesh",
  "lastName": "Gupta",
  "roles": [
    "ADMIN",
    "MANAGER"
  ],
  "birthDate": "17/06/2014"
}

8. Gson setVersion() - 版本支持

如果您正在使用的类文件已在不同版本中进行了修改,并且使用@Since注解了字段,则可以使用此功能。 您需要做的就是使用GsonBuildersetVersion()方法。

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());

//Specify the version like this
gsonBuilder.setVersion(1.0);

Gson gson = gsonBuilder.create();

8.1 Employee.java中以各种版本添加的字段

public class Employee
{
   @Since(1.0)
   private Integer id;
   private String firstName;
   private String lastName;

   @Since(1.1)
   private List<String> roles;

   @Since(1.2)
   private Date birthDate;

   //Setters and Getters
}

Gson @Since示例

//Using version 1.0 fields
gsonBuilder.setVersion(1.0);

Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta"}

/////////////////////////////////////////////////////////////

//Using version 1.1 fields
gsonBuilder.setVersion(1.1);

Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}

/////////////////////////////////////////////////////////////

//Using version 1.2 fields
gsonBuilder.setVersion(1.2);

Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"],"birthDate":"17/06/2014"}

9.更多的 Gson 教程

  1. Gson - GsonBuilder教程
  2. Gson – 序列化和反序列化 JSON
  3. Gson – 序列化和反序列化映射
  4. Gson – 序列化和反序列化集合
  5. Gson – 序列化和反序列化数组
  6. Gson - @SerializedName注解示例
  7. Gson- Jersey + Gson 示例

这就是这个非常有用的 java gson 库的全部内容,可以将对象转换为 JSON 。 如果您有任何疑问或反馈,请发表评论。

学习愉快!

参考

GSON 用户指南