標籤:
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 plaincopy
- Gson gson = new GsonBuilder()
- .registerTypeAdapter(Timestamp.class, new TimestampAdapter())
- .create();
3,自己寫的一個 Timestamp 類型適配器
[java] view plaincopy
- 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)