GSON LocalDateTime Serialization and Deserialization Example

In this GSON example, we will write custom serializer and deserializer for LocalDateTime class.

Order POJO Class - object to be serialized and deserialized

Let's first define an object to be serialized and deserialized - Order.java
class Order {
    private int id;
    private String orderName;
    private String orderDesc;
    private LocalDate orderCreatedDate;
    private LocalDateTime orderCreatedDateTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getOrderName() {
        return orderName;
    }

    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }

    public String getOrderDesc() {
        return orderDesc;
    }

    public void setOrderDesc(String orderDesc) {
        this.orderDesc = orderDesc;
    }

    public LocalDate getOrderCreatedDate() {
        return orderCreatedDate;
    }

    public void setOrderCreatedDate(LocalDate orderCreatedDate) {
        this.orderCreatedDate = orderCreatedDate;
    }

    public LocalDateTime getOrderCreatedDateTime() {
        return orderCreatedDateTime;
    }

    public void setOrderCreatedDateTime(LocalDateTime orderCreatedDateTime) {
        this.orderCreatedDateTime = orderCreatedDateTime;
    }

    @Override
    public String toString() {
        return "Order [id=" + id + ", orderName=" + orderName + ", orderDesc=" + orderDesc + ", orderCreatedDate=" +
            orderCreatedDate + ", orderCreatedDateTime=" + orderCreatedDateTime + "]";
    }
}

Custom GSON LocalDateTimeSerializer

class LocalDateTimeSerializer implements JsonSerializer < LocalDateTime > {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss");

    @Override
    public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDateTime));
    }
}
Note that we are formatting default local date "2018-10-26T11:09:05" to "27::Oct::2018 14::35::13".

Custom GSON LocalDateTimeDeserializer

class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
        return LocalDateTime.parse(json.getAsString(),
            DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss").withLocale(Locale.ENGLISH));
    }
}

Register custom serializer and deserializer

GsonBuilder gsonBuilder = new GsonBuilder();

gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());

gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());

Gson gson = gsonBuilder.setPrettyPrinting().create();

References


Comments