26.md 11.9 KB
Newer Older
W
wizardforcel 已提交
1
# Gson – 快速指南
W
wizardforcel 已提交
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

> 原文: [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
```

W
wizardforcel 已提交
27
## 1.先决条件和依赖项
W
wizardforcel 已提交
28

W
wizardforcel 已提交
29
#### 1.1 POJO 课程
W
wizardforcel 已提交
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

在介绍示例之前,让我们先准备一个 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 + "]";
   }
}

```

W
wizardforcel 已提交
62
#### 1.2 Maven 依赖
W
wizardforcel 已提交
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

```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)。 继续检查一下。

W
wizardforcel 已提交
100
## 3\. Gson toJson()– 将 Java 对象转换为 JSON 字符串
W
wizardforcel 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

要将**将对象转换为 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"]}

```

W
wizardforcel 已提交
124
## 4\. 3\. Gson fromJson()– 将 JSON 字符串转换为 Object
W
wizardforcel 已提交
125 126 127 128 129 130 131 132 133 134 135 136

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

```java
Gson gson = new Gson();

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

```

W
wizardforcel 已提交
137
程序输出:
W
wizardforcel 已提交
138 139 140 141 142 143

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

```

W
wizardforcel 已提交
144
## 5\. Gson InstanceCreator – 给定对象中不存在无参构造函数时
W
wizardforcel 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

在大多数情况下,即使任何类都不提供默认的无参数构造函数, **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));

```

W
wizardforcel 已提交
223
程序输出:
W
wizardforcel 已提交
224 225 226 227 228 229 230 231 232 233 234 235

```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*** ”格式编写日期格式。

W
wizardforcel 已提交
236
#### 6.1 Gson 定制序列化器
W
wizardforcel 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

```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));
   }
}

```

W
wizardforcel 已提交
259
#### 6.2 Gson 定制解串器
W
wizardforcel 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

```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;
   }
}

```

W
wizardforcel 已提交
290
#### 6.3 注册自定义序列化器和反序列化器
W
wizardforcel 已提交
291 292 293 294 295 296 297 298 299 300

现在,您可以在 **`GsonBuilder`** 中注册这些串行器和解串器,如下所示:

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

```

W
wizardforcel 已提交
301
#### 6.4 Gson 定制序列化器和反序列化器示例
W
wizardforcel 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

串行器和解串器的完整示例如下。

```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));

```

W
wizardforcel 已提交
328
程序输出:
W
wizardforcel 已提交
329 330 331 332 333 334 335 336

```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]	

```

W
wizardforcel 已提交
337
## 7\. Gson setPrettyPrinting()– 精美打印 JSON 输出
W
wizardforcel 已提交
338

W
wizardforcel 已提交
339
Gson 提供的默认 JSON 输出是紧凑的 JSON 格式。 这意味着在输出 JSON 结构中将没有任何空格。 要生成更具可读性和美观的 JSON,请使用`GsonBuilder`中的 **setPrettyPrinting()**
W
wizardforcel 已提交
340 341 342 343 344 345 346

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

```

W
wizardforcel 已提交
347
程序输出:
W
wizardforcel 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

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

```

W
wizardforcel 已提交
363
## 8\. Gson setVersion()- 版本支持
W
wizardforcel 已提交
364

W
wizardforcel 已提交
365
如果您正在使用的类文件已在不同版本中进行了修改,并且使用[`@Since`](https://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/annotations/Since.java "since")注释了字段,则可以使用此功能。 您需要做的就是使用`GsonBuilder`**setVersion()**方法。
W
wizardforcel 已提交
366 367 368 369 370 371 372 373 374 375 376 377 378 379

```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();

```

W
wizardforcel 已提交
380
#### 8.1 在 Employee.java 中以各种版本添加的字段
W
wizardforcel 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430

```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/)
W
wizardforcel 已提交
431 432 433 434
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/)
W
wizardforcel 已提交
435
6.  [Gson-@SerializedName 注释示例](https://howtodoinjava.com/library/gson-serializedname/)
W
wizardforcel 已提交
436
7.  [Gson- 球衣+ Gson 示例](https://howtodoinjava.com/jersey/jax-rs-gson-example/)
W
wizardforcel 已提交
437 438 439 440 441 442 443 444

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

学习愉快!

参考

[GSON 用户指南](https://sites.google.com/site/gson/gson-user-guide "google gson")