Monday, September 16, 2013

Custom JSON Serialization and Deserialization  using GSON API

  Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc). Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts:

  • Json Serialiers: Need to define custom serialization for an object 
  • Json Deserializers: Needed to define custom deserialization for a type Instance Creators: Not needed if no-args constructor is available or a deserializer is registered

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(MyType2.class, new MyTypeAdapter());
gson.registerTypeAdapter(MyType.class, new MySerializer());
gson.registerTypeAdapter(MyType.class, new MyDeserializer());
gson.registerTypeAdapter(MyType.class, new MyInstanceCreator());

registerTypeAdapter call checks if the type adapter implements more than one of these interfaces and register it for all of them. Writing a Serializer Here is an example of how to write a custom serializer for JodaTime DateTime class.

private class DateTimeSerializer implements JsonSerializer{
  public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(src.toString());

 Gson calls toJson() when it runs into a DateTime object during serialization. Writing a Deserializer Here is an example of how to write a custom deserializer for JodaTime

DateTime class
private class DateTimeDeserializer implements JsonDeserializer{
  public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException {
    return new DateTime(json.getAsJsonPrimitive().getAsString());

Gson calls fromJson() when it needs to deserialize a JSON string fragment into a DateTime object Finer points with Serializers and Deserializers.
 Often you want to register a single handler for all generic types corresponding to a raw type. For example, suppose you have an "Id" class for Id representation/translation (i.e. an internal vs. external representation). Id type that has same serialization for all generic types.  Essentially write out the id value. Deserialization is very similar but not exactly the same.
  You need to call "new Id(Class, String)" which returns an instance of Id Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say Id needed special handling). 
  The Type parameter for the toJson and from Json contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type

No comments:

Post a Comment