Skip to content

Instantly share code, notes, and snippets.

@ionull
Created March 4, 2014 13:17
Show Gist options
  • Save ionull/9346357 to your computer and use it in GitHub Desktop.
Save ionull/9346357 to your computer and use it in GitHub Desktop.
Gson DateTime adapter converter joda-time retrofit from https://sites.google.com/site/gson/gson-type-adapters-for-common-classes-1
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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment