Gson 基础教程 —— 自定义类型适配器(TypeAdapter)
2013-01-05 14:28
351 查看
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); } }
相关文章推荐
- Gson 基础教程 —— 自定义类型适配器(TypeAdapter)
- Android自定义账户类型和同步适配器模式 Custom Account Type & SyncAdapter
- WCF基础教程(四)——数据契约实现传送自定义数据类型
- Adapter类型控件之BaseAdapter(基础适配器)优化
- Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型
- Android 基础入门教程-Adapter(适配器)
- Gson-----9、注册TypeAdapter及处理Enum类型
- Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型
- Gson之实例六-注册TypeAdapter及处理Enum类型
- 六.OC基础--1. id和instancetype类型,2.动态类型检测,3.响应方法,构造方法,4.重写构造方法,5.自定义构造方法
- WordPress中设置Post Type自定义文章类型的实例教程
- 【转】 Json转换利器Gson之实例五-注册TypeAdapter及处理Enum类型
- 深入Atlas系列:Web Sevices Access in Atlas示例(5) - 自定义TypeConverter把基础类型转换为复杂类型
- Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型
- Gson注册TypeAdapter及处理Enum类型
- 深入Atlas系列:Web Sevices Access in Atlas示例(5) - 自定义TypeConverter把基础类型转换为复杂类型
- WordPress中设置Post Type自定义文章类型的实例教程
- 深入Atlas系列:Web Sevices Access in Atlas示例(5) - 自定义TypeConverter把基础类型转换为复杂类型
- Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型
- android-继承BaseAdapter自定义适配器基础