Recent site activity

Gson Type Adapters for Common Classes

JodaTime Classes

DateTime

  private static class DateTimeTypeConverter
      implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
@Override public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(src.toString());
}
@Override public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
throws JsonParseException {
try {
return new DateTime(json.getAsString());
} catch (IllegalArgumentException e) {
// May be it came in formatted as a java.util.Date, so try that
Date date = context.deserialize(json, Date.class);
return new DateTime(date);
}
}
}

Instant

  private static class InstantTypeConverter
      implements JsonSerializer<Instant>, JsonDeserializer<Instant> {
@Override public JsonElement serialize(Instant src, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(src.getMillis());
}
@Override public Instant deserialize(JsonElement json, Type type, JsonDeserializationContext context)
throws JsonParseException {
return new Instant(json.getAsLong());
}
}

Comments