I\'m using GSON to serialise some object graphs to JSON. These objects graphs use Joda Time entities (DateTime, LocalTime etc).
The top Go
I used the answers above to do a little helper that will handle both serialization and deserialization for model objects containing DateTime variables.
public static Gson gsonDateTime() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new JsonSerializer() {
@Override
public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
}
})
.registerTypeAdapter(DateTime.class, new JsonDeserializer() {
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
DateTime dt = ISODateTimeFormat.dateTime().parseDateTime(json.getAsString());
return dt;
}
})
.create();
return gson;
}