GSON Custom Serialization And Deserialization
GSON Custom serialization and deserialization is often necessary when working with library classes like date and time. Gson allows you to register your own custom serializers and deserializers. The following example will show you how to create your own and how to register them with Gson.
We can register serializers and deserializers for a specific type using the GsonBuilder#registerTypeAdapter(type, typeAdapter)
. In this example we used the DateTime
class of the joda-time library.
package com.memorynotfound.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.joda.time.DateTime;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
public class CustomSerializer {
public static void main(String... args){
Gson gson = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new DateTimeSerializer())
.registerTypeAdapter(DateTime.class, new DateTimeDeserializer())
.create();
String json = gson.toJson(new DateTime());
System.out.println(json);
DateTime date = gson.fromJson(json, DateTime.class);
}
}
Here is an example of how to write a custom serializer for joda-time DateTime
class. We need to implement the JsonSerializer
and override the serialize()
method which will be called when Gson runs into a DateTime
object during serialization.
package com.memorynotfound.json;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.joda.time.DateTime;
import java.lang.reflect.Type;
public class DateTimeSerializer implements JsonSerializer {
@Override
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
}
Here is an example of how to write a custom deserializer for joda-time DateTime
class. We need to implement the JsonDeserializer
interface and override the deserialize()
method which will be called when gson needs to deserialize a JSON string fragment into a DateTime
object.
package com.memorynotfound.json;
import com.google.gson.*;
import org.joda.time.DateTime;
import java.lang.reflect.Type;
public class DateTimeDeserializer implements JsonDeserializer {
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new DateTime(json.getAsJsonPrimitive().getAsString());
}
}