gson使用指南
1. 依赖包
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>2. gson的基本用法
2.1 基本数据类型的解析与生成
Gson gson = new Gson();
Integer fromJson = gson.fromJson("100", Integer.class);// 100
Boolean fromJson2 = gson.fromJson("true", Boolean.class);// true
String fromJson3 = gson.fromJson("100", String.class);// 100
log.info("{},{},{}", fromJson, fromJson2, fromJson3);
String jsonNumber = gson.toJson(100); // 100
String jsonBoolean = gson.toJson(false); // false
String jsonString = gson.toJson("String"); //"String"
log.info("{},{},{}",jsonNumber, jsonBoolean, jsonString);2.2 POJO类的生成与解析
3. 属性重命名 @SerializedName 注解的使用
@SerializedName 注解的使用3.1 为POJO字段提供备选属性名
4. Gson中使用泛型
5. 使用GsonBuilder导出null值、格式化输出、日期时间
5.1 默认null字段是不显示的
5.2 格式化日期
6. 字段过滤的几种方法
6.1 基于@Expose注解
6.2 基于版本
6.3 基于访问修饰符
7. 禁用特殊字符转移
Last updated
Was this helpful?