Gson 基础教程 —— 自定义类型适配器(TypeAdapter)

1,实现一个类型适配器(TypeAdapter)

自定义类型适配器需要实现两个接口:

JsonSerializer<T>

JsonDeserializer<T>

和两个方法:

[java] view plaincopy
 
  1. //序列化  
  2. public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);  
[java] view plaincopy
 
  1. //反序列化  
  2. public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)  
  3.       throws JsonParseException;  

其中 JsonElement 的类层次为:

2,注册类型适配器

[java] view plaincopy
 
  1. Gson gson = new GsonBuilder()  
  2.                     .registerTypeAdapter(Timestamp.class, new TimestampAdapter())  
  3.                     .create();  

3,自己写的一个 Timestamp 类型适配器

[java] view plaincopy
 
    1. package com.gdsc.core.adapter;  
    2.   
    3. import java.lang.reflect.Type;  
    4. import java.sql.Timestamp;  
    5.   
    6. import com.google.gson.JsonDeserializationContext;  
    7. import com.google.gson.JsonDeserializer;  
    8. import com.google.gson.JsonElement;  
    9. import com.google.gson.JsonParseException;  
    10. import com.google.gson.JsonPrimitive;  
    11. import com.google.gson.JsonSerializationContext;  
    12. import com.google.gson.JsonSerializer;  
    13.   
    14. /** 
    15.  * Gson TypeAdapter 
    16.  * 实现了 Timestamp 类的 json 化 
    17.  * @author linwei 
    18.  * 
    19.  */  
    20. public class TimestampAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {  
    21.   
    22.     @Override  
    23.     public Timestamp deserialize(JsonElement json, Type typeOfT,  
    24.             JsonDeserializationContext context) throws JsonParseException {  
    25.         if(json == null){  
    26.             return null;  
    27.         } else {  
    28.             try {  
    29.                 return new Timestamp(json.getAsLong());  
    30.             } catch (Exception e) {  
    31.                 return null;  
    32.             }  
    33.         }  
    34.     }  
    35.   
    36.     @Override  
    37.     public JsonElement serialize(Timestamp src, Type typeOfSrc,  
    38.             JsonSerializationContext context) {  
    39.         String value = "";  
    40.         if(src != null){  
    41.             value = String.valueOf(src.getTime());  
    42.         }  
    43.         return new JsonPrimitive(value);  
    44.     }  
    45.       
    46. }  
原文地址:https://www.cnblogs.com/huangcongcong/p/4766358.html