多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Gson – 快速指南 > 原文: [https://howtodoinjava.com/gson/google-gson-tutorial/](https://howtodoinjava.com/gson/google-gson-tutorial/) [**Gson**](https://sites.google.com/site/gson/ "google gson")(由 Google 提供)是可用于*将 Java 对象转换为 JSON 字符串*的 Java 库。 此外,它还可以用于*将 JSON 字符串转换为等效的 Java 对象*。 还有其他一些 Java 库也可以执行此转换,但是 Gson 处于极少数情况,不需要任何预先注解的 Java 类或 Java 类的源代码。 **Gson** 还支持旧的 Java 类,这些类中不支持泛型来提供类型信息。 它只是与这些旧式类一起正常工作。 在这个 **gson 教程**中,我仅给出一些示例,这些示例可以用 Gson 执行。 ```java 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 类,该类将在给定的示例中使用。 ```java 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 依赖 ```java <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> ``` 在 gradle 中,请使用以下依赖项。 ```java compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5' ``` ## 2.创建 Gson 对象 Gson 对象可以通过两种方式创建。 第一种方法为您准备了快速的 Gson 对象,可以进行更快的编码,而第二种方法使用`GsonBuilder`来构建更复杂的 Gson 对象。 ```java //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`对象提供许多其他[有用选项](https://static.javadoc.io/com.google.code.gson/gson/2.7/com/google/gson/GsonBuilder.html)。 继续检查一下。 ## 3\. Gson `toJson() `– 将 Java 对象转换为 JSON 字符串 要将**将对象转换为 json**,请使用`toJson()`方法。 ```java 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)); ``` 程序输出。 ```java {"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]} ``` ## 4\. 3\. Gson `fromJson()` – 将 JSON 字符串转换为对象 要**将 json 解析为对象**,请使用 **`fromJson()`** 方法。 ```java Gson gson = new Gson(); System.out.println( gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER']}", Employee.class)); ``` 程序输出: ```java Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER]] ``` ## 5\. Gson `InstanceCreator`– 给定对象中不存在无参构造器时 在大多数情况下,即使任何类都不提供默认的无参数构造器, **Gson** 库也足以创建实例。 但是,如果使用无参数构造器的类发现任何问题,则可以使用`InstanceCreator`支持。 使用它之前,您需要先向 Gson 注册 Java 类类型的`InstanceCreator`。 例如,`Department`没有任何默认构造器。 ```java 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`: ```java 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`,如下所示: ```java class DepartmentInstanceCreator implements InstanceCreator<Department> { public Department createInstance(Type type) { return new Department("None"); } } ``` 现在,如下使用上述`InstanceCreator`。 ```java 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)); ``` 程序输出: ```java 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 自定义序列化器 ```java 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 自定义反序列化器 ```java 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`中注册这些串行器和反序列化器,如下所示: ```java GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer()); ``` #### 6.4 Gson 自定义序列化器和反序列化器示例 串行器和反序列化器的完整示例如下。 ```java 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)); ``` 程序输出: ```java {"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()`。 ```java Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonOutput = gson.toJson(employee); ``` 程序输出: ```java { "id": 1, "firstName": "Lokesh", "lastName": "Gupta", "roles": [ "ADMIN", "MANAGER" ], "birthDate": "17/06/2014" } ``` ## 8\. Gson `setVersion()` - 版本支持 如果您正在使用的类文件已在不同版本中进行了修改,并且使用[`@Since`](https://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/annotations/Since.java "since")注解了字段,则可以使用此功能。 您需要做的就是使用`GsonBuilder`的`setVersion()`方法。 ```java 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`中以各种版本添加的字段 ```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`示例 ```java //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`教程](https://howtodoinjava.com/library/gson-gsonbuilder-configuration/) 2. [Gson – 序列化和反序列化 JSON](https://howtodoinjava.com/library/gson-serialize-deserialize-json/) 3. [Gson – 序列化和反序列化映射](https://howtodoinjava.com/java/serialization/gson-serialize-deserialize-hashmap/) 4. [Gson – 序列化和反序列化集合](https://howtodoinjava.com/library/gson-serialize-deserialize-set/) 5. [Gson – 序列化和反序列化数组](https://howtodoinjava.com/library/gson-parse-json-array/) 6. [Gson - `@SerializedName`注解示例](https://howtodoinjava.com/library/gson-serializedname/) 7. [Gson- Jersey + Gson 示例](https://howtodoinjava.com/jersey/jax-rs-gson-example/) 这就是这个非常有用的 java gson 库的全部内容,可以将**对象转换为 JSON** 。 如果您有任何疑问或反馈,请发表评论。 学习愉快! 参考 [GSON 用户指南](https://sites.google.com/site/gson/gson-user-guide "google gson")