GSON is simple and easy to use Open-source API to convert JSON formatted data to JAVA Objects and JAVA Object to JSON Representation.

Table Of Contents:
  1. Gson Overview
  2. Gson Initialization
  3. Convert Java Objects to JSON / JSON to java Objects using default Gson configuration
  4. Format JSON Response / Pretty print JSON response
  5. Date Conversion
  6. Exclude specific fields using transient keyword
  7. Serialize specific elements only using @Expose
  8. Serialize nulls
  9. Serialize field with different name using Gson annotation - @SerializeName
  10. Field naming support
  11. Exclude Specific fields and Data Types using Exclusion Strategy
  12. Custom Serialization by implementing JsonSerializer
  13. References

1. Gson Overview

Gson is opensource library provided by google to handle conversion of Java Objects into JSON representation and JSON to Java Objects.
Gson can be added to projects in following ways.

Gson Maven Dependency

If your project is using maven as build tool, add following dependency to pom.xml to add gson to Java project.

   <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.7</version>
      <scope>compile</scope>
    </dependency>

Gson Grails Dependency

For Grails based java project, update build.grails to add gson to project.


dependencies {
    compile 'com.google.code.gson:gson:2.7'
}

If you are not using any of the above approaches, you can add Gson Jar directly to classpath or build path.

Gson Provides simple API to convert Java to/from JSON representation.

  • toJson(someObj) – Converts Java Object to Json representation.
  • fromJson(JsonFormatString, JavaClass) – Converts JSON representation to Java Object

2. Gson Initialization

Gson object can be created in one of the following 2 ways.

Option 1: Using Default option

    Gson gson=new Gson();

This approach sets many of the default options that are required for JSON conversion.

Option 2: Allows customization

     Gson gson=new GsonBuilder()
       .excludeFieldsWithoutExposeAnnotation() // Specifies Gson to convert @Expose annotated fields only.
       .setDateFormat("MMM dd,yyyy")   // Allows setting default date format to be used during conversion
       .setPrettyPrinting()  // Formats compact JSON string into properly formatted JSON representation
       .create();

There are many other customization options allowed apart from the options specified in above code snippet.

3. Convert Java Objects to JSON / JSON to java Objects using default Gson configuration( new Gson())

public static void main( String[] args )
    {        
        Gson gson=new Gson(); // Gson is instantiated with default options
        String jsonString=gson.toJson(populatePerson());
        System.out.println("JAVA to JSON:"+jsonString);

        Person pers=gson.fromJson(jsonString, Person.class);
        System.out.println("JSON to Java:"+pers);
    }
	
	private static Person populatePerson(){
		Person pers=new Person();
		pers.setAge(30);
		pers.setFirstname("Venkat");
		pers.setLastName("Gutta");	
		List<Address> addressList=new ArrayList<Address>();
		addressList.add(new Address("101 Street",null,"Dallas","TX",75210,"Mailing"));
		addressList.add(new Address("202 Street",null,"Dallas","TX",75999,"Physical"));
		pers.setAddrList(addressList);
		return pers;
	}

Output:

JAVA to JSON:{“firstname”:”Venkat”,”lastName”:”Gutta”,”age”:30,”addrList”:[{“addrLine1″:”101 Street”,”city”:”Dallas”,”state”:”TX”,”zipCode”:75210,”typeCode”:”Mailing”},{“addrLine1″:”202 Street”,”city”:”Dallas”,”state”:”TX”,”zipCode”:75999,”typeCode”:”Physical”}]}
JSON to Java:Person [firstname=Venkat, lastName=Gutta, dateOfBirth=null, age=30, addrList=[Address [addrLine1=101 Street, addrLine2=null, city=Dallas, state=TX, zipCode=75210, typeCode=Mailing], Address [addrLine1=202 Street, addrLine2=null, city=Dallas, state=TX, zipCode=75999, typeCode=Physical]]]

4. Format JSON Response / Pretty print JSON response

For custom configuration, use GsonBuilder to create Gson instance. GsonBuilder allows setting custom configuration. To enable pretty printing, we need to invoke GsonBuilder().setPrettyPrinting().
Replace Gson gson=new Gson(); with Gson gson=GsonBuilder().setPrettyPrinting().create();

Output:

     
{
  "firstname": "First Name",
  "lastName": "Last Name",
  "age": 30,
  "addrList": [
    {
      "addrLine1": "101 Street",
      "city": "Dallas",
      "state": "TX",
      "zipCode": 75210,
      "typeCode": "Mailing"
    },
    {
      "addrLine1": "202 Street",
      "city": "Dallas",
      "state": "TX",
      "zipCode": 75999,
      "typeCode": "Physical"
    }
  ]
}

5. Date Conversion

To address date format issues, Gson provided an option to set date format during Gson instance creation.We can observe, along with configuring pretty print, we also configured date format. Setting Date format allows Gson to understand converting Date object to JSON representation as well converting JSON representation of date to Java Date.


//Person Bean
public class Person {	
	public Person(String firstName, String lastName, int age,Date dateOfBirth) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.dateOfBirth = dateOfBirth;		
	}
	
	String firstName;
	String lastName;	
	int age;	
	Date dateOfBirth;
}
// Code in Main Class
 public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd")
        		.create();
        Person pers=new Person("Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)));
        System.out.println(gson.toJson(pers));
       
    }	

Output:

{
  "firstName": "Venkat",
  "lastName": "Gutta",
  "age": 30,
  "dateOfBirth": "1986-01-01"
}

6. Exclude specific fields using transient

Gson provided a simple approach to exclude fields from serialization using transient modifier. In the below code, we can see firstName is NOT serialized.

public class Person {
	
	public Person(String firstName, String lastName, int age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
        private transient String firstName;
	private String lastName;	
	private int age;	
}
//Main Class
public class App 
{
     public static void main( String[] args )
    {        
        Gson gson=new Gson();
        Person pers=new Person("Venkat","Gutta",30);
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
       
    }	
}

Output:
JAVA to JSON:{
“lastName”: “Gutta”,
“age”: 30
}

7. Serialize specific elements only using @Expose

To utilize this option, we need to configure Gson to consider elements/fields marked with @Expose annotation. This can be done with GsonBuilder.excludeFieldsWithoutExposeAnnotation(). In the below code, we can see only firstName is serialized.

public class Person {
	
	public Person(String firstName, String lastName, int age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	@Expose
	String firstName;
	String lastName;	
	int age;	
}
//Main Class
public class App 
{
     public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        Person pers=new Person("Venkat","Gutta",30);
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
       
    }	
}

Output: JAVA to JSON:{“firstName”:”Venkat”}

8. Serialize nulls

Default Gson configuration will not serialize nulls. If you want to serialize nulls, you can do so by invoking GsonBuilder.serializeNulls() during Gson instance creation.

public class Person {
	public Person(String firstName){
		super();
		this.firstName = firstName;
	}	
	
	String firstName;
	String lastName;	
	Integer age;	
	Date dateOfBirth;
}
// Main Class
public class App 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.serializeNulls()
        		.create();
        Person pers=new Person("Venkat");
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
       
    }	
	
}

Output:

JAVA to JSON:{
“firstName”: “Venkat”,
“lastName”: null,
“age”: null,
“dateOfBirth”: null

}

9. Serialize field with different name using Gson annotation – @SerializeName

Gson provided @SerializeName() annotation support addressing different naming to fields during serialization.In the below example code, we can see “_fname” in java bean is serialized with “firstName” in JSON object format.

public class Person {
	public Person(String _fname, String _lname, int _age, Date _dateOfBirth) {
		super();
		this._fname = _fname;
		this._lname = _lname;
		this._age = _age;
		this._dateOfBirth = _dateOfBirth;
	}
	@SerializedName("firstName")
	private String _fname;	
	private String _lname;
	private int _age;	
	private Date _dateOfBirth;
}
// Main Class
public class App 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd")
        		.create();
        Person pers=new Person("Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)));
        System.out.println("JAVA to JSON:"+gson.toJson(pers));        
       
    }	
	
}

Output:

JAVA to JSON:{
“firstName”: “Venkat”,
“_lname”: “Gutta”,
“_age”: 30,
“_dateOfBirth”: “1986-01-01”
}

10. Field naming support

Gson supports various Field naming requirements with following Field naming policies.

  • FieldNamingPolicy.LOWER_CASE_WITH_DASHES – Ex: firstName => first-name
  • FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES – Ex: firstName => first_name
  • FieldNamingPolicy.UPPER_CAMEL_CASE – Ex: firstName => FirstName
  • FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES – Ex: firstName => Fist Name

Below example covers FieldNamingPolicy.LOWER_CASE_WITH_DASHES usage.

public class Person {

	public Person(String fistName, String lastName, int _age, Date dateOfBirth) {
		super();
		this.fistName = fistName;
		this.lastName = lastName;
		this._age = _age;
		this.dateOfBirth = dateOfBirth;
	}
	private String fistName;	
	private String lastName;
	private int _age;	
	private Date dateOfBirth;
}
// Main Class
public class App 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd").setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
        		.create();
        Person pers=new Person("Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)));
        System.out.println("JAVA to JSON:"+gson.toJson(pers));        
       
    }	
	
}

Output:

JAVA to JSON:{
“fist-name”: “Venkat”,
“last-name”: “Gutta”,
“_age”: 30,
“date-of-birth”: “1986-01-01”
}

11. Exclude Specific fields and Data Types using Exclusion Strategy

Apart from using transient modifier and @Expose annotation, Gson custom exclusion strategies are provided to address various real world scenarios.Custom Exclusion Strategy can be implemented using below approaches.

  • Exclude fields using custom annotation
  • Exclude Data Types

For more information, please refer How to exclude fields using Exclusion Strategy

12. Custom Serialization by implementing JsonSerializer

In case if we need to handle serialization mechanism for certain data types, we can use custom serialization approach. It is covered in detail in Gson Custom Serialization Example.

13. References

Gson User Guide

Gson tutorial : Simple Java to JSON examples

One thought on “Gson tutorial : Simple Java to JSON examples

Leave a Reply

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