Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thermosym/1ca420c713c3d8f5a8262741e8863902 to your computer and use it in GitHub Desktop.
Save thermosym/1ca420c713c3d8f5a8262741e8863902 to your computer and use it in GitHub Desktop.
Gson ISODateTime serializer/deserializer for Joda DateTime
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
public class DateTimeConverter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
private DateTimeFormatter fmt;
public DateTimeConverter() {
fmt = ISODateTimeFormat.dateTimeNoMillis();
}
public DateTimeConverter(DateTimeFormatter fmt) {
this.fmt = fmt;
}
@Override
public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
try {
return new JsonPrimitive(src.toString(fmt));
} catch (Exception e) {
System.out.println(e.getMessage());
}
return new JsonPrimitive("");
}
@Override
public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
throws JsonParseException {
try {
return fmt.parseDateTime(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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment