In this GSON example, we will write custom serializer and deserializer for LocalDate class.
Order.java - The 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 LocalDateSerializer
class LocalDateSerializer implements JsonSerializer < LocalDate > {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");
@Override
public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDate));
}
}
Note that we are formatting default local date "2018-10-26" to "27-Oct-2018".
Custom GSON LocalDateDeserializer
class LocalDateDeserializer implements JsonDeserializer < LocalDate > {
@Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDate.parse(json.getAsString(),
DateTimeFormatter.ofPattern("d-MMM-yyyy").withLocale(Locale.ENGLISH));
}
}
Register custom serializer and deserializer
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
Check out complete example at https://www.javaguides.net/2018/10/gson-custom-serialization-and-deseriliazation-examples.html.
References
Gson
Java
JSON
Comments
Post a Comment