Sometimes default serialization/deserialization used by GSON is not sufficient enough and we need a custom behavior to be applied while serializing/deserializing objects to/from JSON. This can easily be done by writing custom JsonSerializer
& JsonDeserializer
implementation and hooking them with GsonBuilder
.
We will write a custom implementation to handle a date property in our example pojo.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.websystique.json</groupId> <artifactId>GsonCustomSerializationExample</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>GsonCustomSerializationExample</name> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> </dependencies> </project>
Below pojo contains a date property named ‘promoDate’. We will write our custom implementation to provide the date for this property in a specific format(‘dd/MM/yyyy’).
package com.websystique.json.gson.model; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Car { private String name; private int model; private double price; private Date promoDate; private List<String> colors = new ArrayList<String>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public int getModel() { return model; } public void setModel(int model) { this.model = model; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public List<String> getColors() { return colors; } public void setColors(List<String> colors) { this.colors = colors; } public Date getPromoDate() { return promoDate; } public void setPromoDate(Date promoDate) { this.promoDate = promoDate; } @Override public String toString() { return "Car [name=" + name + ", model=" + model + ", price=" + price + ", promoDate=" + promoDate + ", colors=" + colors + "]"; } }
package com.websystique.json.gson.model; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class CustomDateSerializer implements JsonSerializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(dateFormat.format(date)); } }
package com.websystique.json.gson.model; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; public class CustomDateDeserializer implements JsonDeserializer<Date> { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); public Date deserialize(JsonElement dateStr, Type typeOfSrc, JsonDeserializationContext context) { try { return dateFormat.parse(dateStr.getAsString()); } catch (ParseException e) { e.printStackTrace(); } return null; } }
package com.websystique.json.gson; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.websystique.json.gson.model.Car; import com.websystique.json.gson.model.CustomDateDeserializer; import com.websystique.json.gson.model.CustomDateSerializer; public class GsonCustomSerializationDemo { public static void main(String args[]){ GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting(); /* Register custom serializers with GsonBuilder */ gsonBuilder.registerTypeAdapter(Date.class, new CustomDateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new CustomDateDeserializer()); Gson gson = gsonBuilder.create(); Car car = new Car(); car.setName("AUDI"); car.setModel(2014); car.setPrice(30000); car.setPromoDate( new Date()); car.getColors().add("GRAY"); car.getColors().add("BLACK"); car.getColors().add("WHITE"); String jsonString = gson.toJson(car); // Convert car object to JSON string System.out.println(jsonString); Car car2 = gson.fromJson(jsonString, Car.class);// Convert JSON String to car object System.out.println(car2); } }
Following is the output. You can see that promoDate follows the format mentioned via custom implementation.
{ "name": "AUDI", "model": 2014, "price": 30000.0, "promoDate": "05/06/2015", "colors": [ "GRAY", "BLACK", "WHITE" ] } Car [name=AUDI, model=2014, price=30000.0, promoDate=Fri Jun 05 00:00:00 CEST 2015, colors=[GRAY, BLACK, WHITE]]
That’s it. In the next post we will learn about Gson ExclusionStrategy used to exclude some fields from serializaion/deserialization.
References
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.
In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…
Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…
Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…
Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…
Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…
This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…