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.
- Spring MVC 4+Spring Security 4 + Hibernate Integration Example
- Spring MVC 4+AngularJS Routing with UI-Router Example
- Spring MVC 4+AngularJS Example
- Spring MVC 4 HelloWorld – Annotation/JavaConfig Example
- Spring MVC 4+Hibernate 4+MySQL+Maven integration example
- Spring 4 Hello World Example
- Spring Security 4 Hello World Annotation+XML Example
- Hibernate MySQL Maven Hello World Example (Annotation)
- TestNG Hello World Example
- JAXB2 Helloworld Example
- Spring Batch- Read a CSV file and write to an XML file
Step 1: Include GSON dependency in pom.xml
<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>
Step 2: Sample POJO
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 + "]"; } }
Step 3: Write Custom Date Serializer to convert Java date to JSON string in particular format
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)); } }
Step 4: Write Custom Date Deserializer to convert date from JSON string to Java 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; } }
Step 5: Register custom Serializer/Deserializer with GsonBuilder, Run
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.