I ran into an issue with the default Calendar Serialization in version 1.7.1. The serialization looses milliseconds!! (Lots of libraries miss the fact that the internal representation of Calendar is in milliseconds!!!)
So I had to write custom serialization. The registration is less intuitive. You have to do this:
GsonBuilder gsonB = new GsonBuilder();
gsonB.registerTypeAdapter(Calendar.class, new CalendarSerializer());
gsonB.registerTypeAdapter(GregorianCalendar.class, new CalendarSerializer());
When serializing, the instance class of the field is GregorianCalendar and while de-serializing, the target class has Calendar as the field.
Here is the CalendarSerializer (Note: I loose the timezone)
public class CalendarSerializer implements JsonSerializer<Calendar>, JsonDeserializer<Calendar>{
@Override
public JsonElement serialize(Calendar src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTimeInMillis());
}
@Override
public Calendar deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(json.getAsJsonPrimitive().getAsLong());
return cal;
}
}