Gson 基础教程 —— 自定义类型适配器(TypeAdapter)
2024-09-15 06:24:16
1,实现一个类型适配器(TypeAdapter)
自定义类型适配器需要实现两个接口:
JsonSerializer<T>
JsonDeserializer<T>
和两个方法:
- //序列化
- public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
- //反序列化
- public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
- throws JsonParseException;
其中 JsonElement 的类层次为:
2,注册类型适配器
- Gson gson = new GsonBuilder()
- .registerTypeAdapter(Timestamp.class, new TimestampAdapter())
- .create();
3,自己写的一个 Timestamp 类型适配器
- package com.gdsc.core.adapter;
- import java.lang.reflect.Type;
- import java.sql.Timestamp;
- import com.google.gson.JsonDeserializationContext;
- import com.google.gson.JsonDeserializer;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonParseException;
- import com.google.gson.JsonPrimitive;
- import com.google.gson.JsonSerializationContext;
- import com.google.gson.JsonSerializer;
- /**
- * Gson TypeAdapter
- * 实现了 Timestamp 类的 json 化
- * @author linwei
- *
- */
- public class TimestampAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {
- @Override
- public Timestamp deserialize(JsonElement json, Type typeOfT,
- JsonDeserializationContext context) throws JsonParseException {
- if(json == null){
- return null;
- } else {
- try {
- return new Timestamp(json.getAsLong());
- } catch (Exception e) {
- return null;
- }
- }
- }
- @Override
- public JsonElement serialize(Timestamp src, Type typeOfSrc,
- JsonSerializationContext context) {
- String value = "";
- if(src != null){
- value = String.valueOf(src.getTime());
- }
- return new JsonPrimitive(value);
- }
- }
最新文章
- 不同类型的指针+1之后增加的大小不同(a,&;a的地址是一样的,但意思不一样)
- 编译到底做了什么(***.c ->; ***.o的过程)
- 58. 分析、测试与总结:罗马数字和阿拉伯数字的转换[roman to integer and integer to roman in c++]
- js 获取select 中option 的个数
- Iframe的应用以及父窗口和子窗口的相互访问
- VC6.0环境安装STLport-5.2.1
- 高级私人定制西服品牌:XUAN PRIVE 为定制而生_乐活_onlylady女人志
- 树莓派 (Raspberry Pi) 是什么?普通人怎么玩?(私有云NAS也会有;上传到百度盘的功能nas也有)
- html中embed标签的用法
- (zz)Linux下Gcc生成和使用静态库和动态库详解
- 编译安装CoreSeek-4.1
- python--对于装饰器的理解
- nginx-http-concat资源文件合并模块
- Android版数据结构与算法(七):赫夫曼树
- ABAP WB01 BDC ”No batch input data for screen & &“ ”没有屏幕 & & 的批输入数据“
- vue不通过路由直接获取url中参数的方法示例
- 创建ApplicationContext与BeanFactory时的区别-Spring源码学习之容器的基本实现
- Docker学习笔记之从镜像仓库获得镜像
- Java中的final关键字--浅析
- JVM之JIT