Gson 基础教程 —— 自定义类型适配器(TypeAdapter)
1,实现一个类型适配器(TypeAdapter)
自定义类型适配器须要实现两个接口:java
JsonSerializer<T>sql
JsonDeserializer<T>json
和两个方法:ide
- public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context);
- public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
- throws JsonParseException;
其中 JsonElement 的类层次为:ui

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;
-
- 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);
- }
-
- }
欢迎关注本站公众号,获取更多信息