How to implement custom serializer during Gson based Java to JSON conversion, is covered in this tutorial. Simple Gson examples to exclude fields using Gson annotations can be viewed at Gson tutorial.

1. Gson Custom Serialization- JsonPrimitive Example

In real time applications, entity/beans used in system use encoded values for various data elements to store in database for better processing. If we need to serialize such bean to JSON, we need to convert encoded values into user/UI understandable format.

For instance, Id class is created to address application needs but UI layer does not need to know details of Id object except the id attribute of it.Let’s see how to address it using below example.

1.1 Create POJOs

Create 2 POJOs Id.java,Person.java classes. And Id class is application specific class to preserve id of Person domain.


// Id. Java
public class Id {
	
	private final int value;
	private Id(int value){
		this.value=value;
	}
	public static Id valueOf(int value){
		return new Id(value);
	}
	public String toString(){
		return String.valueOf(value);
	}

}
// Person.java
public class Person {
	
	public Person(Id id,String firstName, String lastName, int age,Date dateOfBirth) {
		super();
		this.id=id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.dateOfBirth = dateOfBirth;			
	}
	private Id id;
	private String firstName;
	private String lastName;	
	private int age;
	private Date dateOfBirth;
}

1.2 Create Custom Serializer for Id class

Since Id is application internal class and we don’t want it to be serialized as is. We will use below custom serializer to serialize Id according our choice. In this example we will use JsonPrimitive to convert Id type.

IdSerializer.java
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class IdSerializer implements JsonSerializer<Id>{

	public JsonElement serialize(Id src, Type typeOfSrc, JsonSerializationContext context) {
		     String idStr = src.toString();	        
	        return new JsonPrimitive(idStr);
	}
}

1.3 Register custom serializer using GsonBuilder.registerTypeAdapter()

Register custom Id serializer (IdSerializer.java) and run application
API: new GsonBuilder.registerTypeAdapter(Class Type,instance of Class)

import java.sql.Date;
import java.time.LocalDate;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class IdSerializerApp 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd")        
        		.registerTypeAdapter(Id.class, new IdSerializer())        		
        		.create();
        
   
        Person pers=new Person(Id.valueOf(10),"Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)));
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
             
    }		
}

Output:

Without Custom Id Serializer(Before) With Custom Id Serializer (After)

{
“id”: {
“value”: 10
},

“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30,
“dateOfBirth”: “1986-01-01”
}

{
“id”: “10”,
“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30,
“dateOfBirth”: “1986-01-01”
}

2. Gson Custom Serialization- JsonObject Example

During custom serialization, if we want to serialize a complex type / Java Object to serialize into multiple name-value pairs, we will use JsonObject.

For instance, Address will have several encoded data elements like State, city and country etc. Instead of creating one more layer,to address conversion of encoded values to UI understandable values, between backend domain representation to JSON Data format, we can use Gson provided custom serialization approach. In this approach, Gson gives better control on serialization.

2.1 Create POJOs

Create 2 POJOs Address.java, Person.java classes. Address domain classis created to hold data from database. Let’s assume, we stored state, city and address type code in integer format.And we need to create Json in UI consumable format. Following example will shows one possiblity how we can get this done.

// Person.java
public class Person {
	
	public Person(String firstName, String lastName, int age,Date dateOfBirth,List<Address> addressList) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.dateOfBirth = dateOfBirth;	
		this.addressList = addressList;
	}
	String firstName;
	String lastName;	
	int age;
	List<Address> addressList;
	Date dateOfBirth;
}
// Address.java
public class Address {
	
	private String addrLine1;
	private String city;
	private String state;
	private int zipCode;
	private String typeCode;
	
	public Address(String addrLine1, String city, String state, int zipCode, String typeCode) {
		super();
		this.addrLine1 = addrLine1;
		this.city = city;
		this.state = state;
		this.zipCode = zipCode;
		this.typeCode = typeCode;
	}
	public String getTypeCode() {
		return typeCode;
	}
	
	public String getAddrLine1() {
		return addrLine1;
	}
	public void setAddrLine1(String addrLine1) {
		this.addrLine1 = addrLine1;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public int getZipCode() {
		return zipCode;
	}
	public void setZipCode(int zipCode) {
		this.zipCode = zipCode;
	}
}

2.2 Create Custom Serializer for Address class

Since Address is application internal class and we don’t want it to be serialized as is. We will use below custom serializer to serialize Address according our choice. In this example we will use JsonObject to convert address attributes to UI understandable format.
In below example, we can see City is converted from integer representation to Text format to be consumed by UI. Same is the case for state and address type code.In this example, i am just showing the possiblity. But in real world applications, we might implement such conversion using reference data from cache.

AddressSerializer.java

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class AddressSerializer implements JsonSerializer<Address>{

	public JsonElement serialize(Address src, Type typeOfSrc, JsonSerializationContext context) {
		JsonObject addressJsonObj=new JsonObject();  
		addressJsonObj.addProperty("addrLine1", src.getAddrLine1());
		addressJsonObj.addProperty("city",convertCityCode(src.getCity()) );
		addressJsonObj.addProperty("state",convertStateCode(src.getState()) );
		addressJsonObj.addProperty("zipcode", src.getZipCode());
		addressJsonObj.addProperty("addrType", convertAddressTypeCode(src.getTypeCode()));
		       
	    return addressJsonObj;        
	    
	}
	
	private String convertCityCode(String code){
		return ("06".equals(code)?"Dallas":null);
	}
	private String convertStateCode(String code){
		return ("01".equals(code)?"Texas":null);
	}
	private String convertAddressTypeCode(String code){
		return ("PA".equals(code)?"Physical":"Mailing");
	}

}

2.3 Register custom serializer using GsonBuilder.registerTypeAdapter()

Register custom Address serializer (AddressSerializer.java) and run application
API: new GsonBuilder.registerTypeAdapter(Class Type,instance of Class)

public class App 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd")
        		.registerTypeAdapter(Address.class, new AddressSerializer())
        		.create();
        
        List<Address> addressList=new ArrayList<Address>();
		addressList.add(new Address("101 Street","06","01",75210,"MA"));
		addressList.add(new Address("202 Street","06","01",75999,"PA"));
		
        Person pers=new Person("Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)),addressList);
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
             
    }		
}

Output:

Without Custom AddressSerializer(Before) With Custom AddressSerializer (After)

{
“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30,
“addressList”: [
{
“addrLine1”: “101 Street”,
“city”: “06”,
“state”: “01”,
“zipCode”: 75210,
“typeCode”: “MA”

},
{
“addrLine1”: “202 Street”,
“city”: “06”,
“state”: “01”,
“zipCode”: 75999,
“typeCode”: “PA”

}
],
“dateOfBirth”: “1986-01-01”
}

{
“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30,
“addressList”: [
{
“addrLine1”: “101 Street”,
“city”: “Dallas”,
“state”: “Texas”,
“zipcode”: 75210,
“addrType”: “Mailing”

},
{
“addrLine1”: “202 Street”,
“city”: “Dallas”,
“state”: “Texas”,
“zipcode”: 75999,
“addrType”: “Physical”

}
],
“dateOfBirth”: “1986-01-01”
}

Gson : Simple custom serializer example

One thought on “Gson : Simple custom serializer example

Leave a Reply

Your email address will not be published. Required fields are marked *