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

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

JsonSerializer<T>

JsonDeserializer<T>

和两个方法:

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

其中 JsonElement 的类层次为:

2,注册类型适配器

  1. Gson gson = new GsonBuilder()
  2. .registerTypeAdapter(Timestamp.class, new TimestampAdapter())
  3. .create();

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

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

最新文章

  1. 不同类型的指针+1之后增加的大小不同(a,&amp;a的地址是一样的,但意思不一样)
  2. 编译到底做了什么(***.c -&gt; ***.o的过程)
  3. 58. 分析、测试与总结:罗马数字和阿拉伯数字的转换[roman to integer and integer to roman in c++]
  4. js 获取select 中option 的个数
  5. Iframe的应用以及父窗口和子窗口的相互访问
  6. VC6.0环境安装STLport-5.2.1
  7. 高级私人定制西服品牌:XUAN PRIVE 为定制而生_乐活_onlylady女人志
  8. 树莓派 (Raspberry Pi) 是什么?普通人怎么玩?(私有云NAS也会有;上传到百度盘的功能nas也有)
  9. html中embed标签的用法
  10. (zz)Linux下Gcc生成和使用静态库和动态库详解
  11. 编译安装CoreSeek-4.1
  12. python--对于装饰器的理解
  13. nginx-http-concat资源文件合并模块
  14. Android版数据结构与算法(七):赫夫曼树
  15. ABAP WB01 BDC ”No batch input data for screen & &“ ”没有屏幕 & & 的批输入数据“
  16. vue不通过路由直接获取url中参数的方法示例
  17. 创建ApplicationContext与BeanFactory时的区别-Spring源码学习之容器的基本实现
  18. Docker学习笔记之从镜像仓库获得镜像
  19. Java中的final关键字--浅析
  20. JVM之JIT

热门文章

  1. Vim的多窗口模式管理
  2. Centos6 安装vnc
  3. int? 类型数据
  4. MyEclipse修改servlet模版
  5. JY05-JavsScript-JS基础01
  6. svg转换工具
  7. Eclipse+maven发布ee项目jar包未发布
  8. 安全管理:IE6安全隐患重重 为何不离不弃
  9. vs2013+sql server2012 +win8.1+entity framework + linq
  10. JavaScript 函数作用域和闭包