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

本文是关于Gson的基础教程,重点讲解如何创建和注册自定义类型适配器(TypeAdapter)。通过实现JsonSerializer<T>和JsonDeserializer<T>接口,并提供转换方法,可以对特定类型如Timestamp进行定制化序列化和反序列化操作。

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);
	}
	
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值