Joda Datetime Custom Serializer and Deserializer
Create the DateTime Type Adapter
import com.google.gson.*;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.lang.reflect.Type;
public class JodaDateTimeAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
private final DateTimeFormatter formatter;
public JodaDateTimeAdapter() {
// Using ISO format as default
this.formatter = ISODateTimeFormat.dateTime();
}
public JodaDateTimeAdapter(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
try {
return new JsonPrimitive(formatter.print(src));
} catch (Exception e) {
throw new JsonParseException("Error serializing DateTime", e);
}
}
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
String dateTimeStr = json.getAsString();
return formatter.parseDateTime(dateTimeStr);
} catch (IllegalArgumentException e) {
throw new JsonParseException("Error parsing DateTime", e);
}
}
}With Multiple Format Support
Usage Examples
Testing Different Scenarios
Configuration with Spring Boot
Key Features of this Implementation:
Last updated