Adding a custom Converter to Gson
suggest changeSometimes you need to serialize or deserialize a field in a particular format. For example, the backend may use yyyy-MM-dd HH:mm for dates, while the POJO uses Joda-Time’s DateTime.
A custom converter can turn those strings into DateTime objects automatically.
/**
* Gson serialiser/deserialiser for converting Joda {@link DateTime} objects.
*/
public class DateTimeConverter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
private final DateTimeFormatter dateTimeFormatter;
@Inject
public DateTimeConverter() {
this.dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
}
@Override
public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(dateTimeFormatter.print(src));
}
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (json.getAsString() == null || json.getAsString().isEmpty()) {
return null;
}
return dateTimeFormatter.parseDateTime(json.getAsString());
}
}
To make Gson use the newly created converter you need to assign it when creating the Gson object:
DateTimeConverter dateTimeConverter = new DateTimeConverter();
Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, dateTimeConverter)
.create();
String s = gson.toJson(DateTime.now());
// this will show the date in the desired format
To deserialize that format, declare the field as DateTime:
public class SomePojo {
private DateTime someDate;
}
When Gson encounters a field of type DateTime, it will call your converter in order to deserialize the field.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents