GSON使用总结

GSON使用总结

一、引入gson版本

 
 com.google.code.gson
 gson
 2.8.5
 

二、两种使用方式

2.1基本使用

 Gson gson = new Gson();

2.2自定义

Gson gson = new GsonBuilder()
.xxxx()
.create(); 

常用使用如下替换xxxx()方法:

  1. setPrettyPrinting(),作用设置json的输出格式;
  2. setFieldNamingPolicy(FieldNamingPolicy.IDENTITY),作用设置序列化字段策略,常用策略;
 2.1.FieldNamingPolicy.IDENTITY 默认属性,不改变字段的属性
 2.2.FieldNamingPolicy.LOWER_CASE_WITH_DASHES 是字段属性小写,并加上-为分割
 2.3.FieldNamingPolicy.LOWER_CASE_WITH_DOTS 是字段属性小写,并加上.为分割
 2.4. FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES 是字段属性小写,并 加上_为分割
 2.5.FieldNamingPolicy.UPPER_CAMEL_CASE 每个单词首字母大写
 2.6.FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES 每个首字母大写并以空格隔开

注:这些策略不会影响标记@SerializedName注解的字段

3. serializeNulls(),作用序列化空字段

4.setExclusionStrategies(new ExclusionStrategy()),作用设置字段是否需要序列化,如果shouldSkipClass(Class) 或shouldSkipField(attribute)方法返回true,将不会序列化和反序列化该类型(字段)


5.excludeFieldsWithoutExposeAnnotation(),需要配合@Expose注解来使用 ,忽略某个字段进行初始化

6.
excludeFieldsWithModifiers(Modifier.STATIC) Modifier.STATIC, 不序列化被 static修饰的字段Modifier.TRANSIENT,不序列化被transient修饰的字段,Modifier.VOLATILE 不序列化被volatile修饰的字段

7.registerTypeAdapter(Type, Object)自定义序列化和反序列化方法

三、常用注解

3.1 @since 指定该字段在序列化和反序列化时在哪个版本显示

public class Employee{
 private Integer id;
 @Since(1.0)
 private String firstName;
 @Since(1.1)
 private String lastName;
 @Since(1.2)
 private String email;
}
Employee employeeObj = new Employee(1, "Lokesh", "Gupta", "[email protected]");
Gson gson = new GsonBuilder()
 .setVersion(1.1)
 .create();
System.out.println(gson.toJson(employeeObj));
只序列化1.1及之前的版本的字段
{
 "id": 1,
 "firstName": "Lokesh",
 "lastName": "Gupta"
}

3.2.@SerializedName按照指定的字段名进行序列化和反序列化 序列化时email以emailId输出,反序列化的时候以emailAddress输入 代码如下

public class Employee
{
 private Integer id;
 private String firstName;
 private String lastName;
 @SerializedName(value = "emailId", alternate = "emailAddress")
 private String email;
}
//序列化代码
Employee emp = new Employee(1001, "Lokesh", "Gupta", "[email protected]");
 
Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
 
System.out.println(gson.toJson(emp));
//序列化输出
{
 "id": 1001,
 "firstName": "Lokesh",
 "lastName": "Gupta",
 "emailId": "[email protected]"
}
//反序列化
String json = "{'id': 1001,"
 + "'firstName': 'Lokesh',"
 + "'lastName': 'Gupta',"
 + "'email': '[email protected]',"
 + "'emailAddress': '[email protected]'}";
 
Gson gson = new GsonBuilder().setPrettyPrinting().create();
 
Employee emp = gson.fromJson(json, Employee.class);
 
System.out.println(emp);
//反序列化输出
Employee [id=1001, firstName=Lokesh, lastName=Gupta, [email protected]]

3.3.@Expose序列化和反序列化是否忽略该字段 @Expose(serialize = false)

private String lastName;
@Expose (serialize = false, deserialize = false)
private String emailAddress;
Gson gson = new GsonBuilder()
 .excludeFieldsWithoutExposeAnnotation()
 .create();
注使用new Gson()来执行 toJson() and fromJson() 方法时不生效的,
transient 与 @Expose (serialize = false, deserialize = false)有相同的效果
 

四、自定义序列化和反序列化

4.1实现JsonSerializer接口

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class BooleanSerializer implements JsonSerializer {
 public JsonElement serialize(Boolean aBoolean, Type type,
 JsonSerializationContext jsonSerializationContext)
 {
 if(aBoolean){
 return new JsonPrimitive(1);
 }
 return new JsonPrimitive(0);
 }
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main
{
 public static void main(String[] args) throws Exception
 {
 Employee emp = new Employee(1, "Lokesh", "Gupta", "[email protected]", true);
 
 Gson gson = new GsonBuilder()
 .registerTypeAdapter(Boolean.class, new BooleanSerializer())
 .setPrettyPrinting()
 .create();
 
 String json = gson.toJson(emp);
 
 System.out.println(json);
 }
}
//输出
{
 "id": 1,
 "firstName": "Lokesh",
 "lastName": "Gupta",
 "email": "[email protected]",
 "active": 1
}
 

4.2JsonDeserializer反序列化接口

//Employee.java
public class Employee
{
 private Integer id;
 private String firstName;
 private String lastName;
 private String email;
 private LocalDate dob;
}
//EmployeeDeserializer.java
public class EmployeeDeserializer implements JsonDeserializer
{
 @Override
 public Employee deserialize(JsonElement json, Type typeOfT,
 JsonDeserializationContext context) throws JsonParseException
 {
 JsonObject jsonObject = json.getAsJsonObject();
 LocalDate localDate = LocalDate.of(
 jsonObject.get("year").getAsInt(),
 jsonObject.get("month").getAsInt(),
 jsonObject.get("day").getAsInt()
 );
 return new Employee(
 jsonObject.get("id").getAsInt(),
 jsonObject.get("firstName").getAsString(),
 jsonObject.get("lastName").getAsString(),
 jsonObject.get("email").getAsString(),
 localDate);
 }
}
public class Main{
 public static void main(String[] args) throws Exception
 {
 String json = "{'id': 1001,"
 + "'firstName': 'Lokesh',"
 + "'lastName': 'Gupta',"
 + "'email': '[email protected]', "
 + "'day': 11, "
 + "'month': 8, "
 + "'year': 2019}";
 
 Gson gson = new GsonBuilder()
 .registerTypeAdapter(Employee.class, new EmployeeDeserializer())
 .create();
 
 Employee employee = gson.fromJson(json, Employee.class);
 
 System.out.println(employee);
 }
}

五、gson反序列化数组,List,Set,Map,如果这些类型作为成员属性和序列化时无须特殊处理

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
1.数组
String userJson = "[{'name': 'Alex','id': 1}, "
 + "{'name': 'Brian','id':2}, "
 + "{'name': 'Charles','id': 3}]";
 
Gson gson = new Gson();
User[] userArray = gson.fromJson(userJson, User[].class);
//2.List
String userJson = "[{'name': 'Alex','id': 1}, "
 + "{'name': 'Brian','id':2}, "
 + "{'name': 'Charles','id': 3}]";
Gson gson = new Gson();
Type userListType = new TypeToken>(){}.getType();
ArrayList userArray = gson.fromJson(userJson, userListType); 
//3.Set
Gson gson = new Gson();
Type setType = new TypeToken>(){}.getType();
Set userSet = gson.fromJson(jsonString, setType);
//4.Map
 HashMap employeeMap = new HashMap<>();
 
 employeeMap.put(1, new Employee(1l, "Alex", LocalDate.of(1990, 01, 01)));
 employeeMap.put(2, new Employee(2l, "Bob", LocalDate.of(1990, 02, 01)));
//Deep clone
 Gson gson = new Gson();
 String jsonString = gson.toJson(employeeMap);
 
 Type type = new TypeToken>(){}.getType();
 HashMap clonedMap = gson.fromJson(jsonString, type);

参考学习:
https://howtodoinjava.com/learningpaths/gson/


分享到:


相關文章: