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

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

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

JsonSerializer<T>

JsonDeserializer<T>

和两个方法:

 

[java]  view plain copy
 
  1. //序列化  
  2. public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);  

 

 

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

 

 

其中 JsonElement 的类层次为:

2,注册类型适配器

 

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

 

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

 

 

[java]  view plain copy
 
    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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值