Created
March 4, 2014 13:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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