Gson 基础教程 —— 自定义类型适配器(TypeAdapter)
2015-08-28 13:58
621 查看
1,实现一个类型适配器(TypeAdapter)
自定义类型适配器需要实现两个接口:JsonSerializer<T>
JsonDeserializer<T>
和两个方法:
[java] view plaincopy
//序列化
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
[java] view plaincopy
//反序列化
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException;
其中 JsonElement 的类层次为:
2,注册类型适配器
[java] view plaincopyGson gson = new GsonBuilder()
.registerTypeAdapter(Timestamp.class, new TimestampAdapter())
.create();
3,自己写的一个 Timestamp 类型适配器
[java] view plaincopypackage 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);
}
}
相关文章推荐
- python实现邮件群发
- mina deploy 时Permission denied (publickey). fatal: The remote end hung up unexpectedly的解决办法。
- Android 关于“NetworkOnMainThreadException”出错提示的原因及解决办法
- eclipse的Android项目不能运行
- java中&和&&的区别
- hdu 1506 Largest Rectangle in a Histogram(单调栈)
- nginx+php(fastcgi)安装教程
- css动画
- Android-插入短信及备份手机中的短信到SD卡
- SQLserver2012-2014数据库 日志和没有日志的数据库恢复办法
- Android学习笔记(十四)
- UIWebView的基本用法(1)
- android中的View组件
- Http调试工具-Fiddler使用指引
- 指针数组 详解
- Cocos2d-x开发系列 磨刀不误砍柴工
- hdu 1084 What Is Your Grade(水题)
- 打包签名与版本号修改
- 数据结构和算法基础
- nim的引用和指针