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/


分享到:


相關文章: