Essential Android Handling JSON with Gson edit forum

Adding a custom Converter to Gson

Sometimes you need to serialize or deserialize some fields in a desired format, for example your backend may use the format “YYYY-MM-dd HH:mm” for dates and you want your POJOS to use the DateTime class in Joda Time.

In order to automatically convert these strings into DateTimes object, you can use a custom converter.

 * Gson serialiser/deserialiser for converting Joda {@link DateTime} objects.
public class DateTimeConverter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {

    private final DateTimeFormatter dateTimeFormatter;

    public DateTimeConverter() {
        this.dateTimeFormatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm");

    public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateTimeFormatter.print(src));

    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)

String s = gson.toJson(;
// this will show the date in the desired format

In order to deserialize the date in that format you only have to define a field in the DateTime format:

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.

Table Of Contents
64 Menu
107 Handling JSON with Gson
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close