Serialization – How to convert Java Object To JSON Object Using Gson API

HOME

The previous tutorials have explained the conversion of Java Object to JSON and JSON payload to Java Objects using Jackson API. This tutorial explains the process to convert Java Object to JSON Payload using Gson API.

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects, including pre-existing objects those you do not have source code.

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa.
  • Allow pre-existing unmodifiable objects to be converted to and from JSON.
  • Extensive support of Java Generics.
  • Allow custom representations for objects.
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types).

Add the below dependency to POM.xml to use Gson API.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

Let us take an example of a JSON.

{
  "firstName" : "Vibha",
  "lastName" : "Singh",
  "age" : 30,
  "salary" : 75000.0,
  "designation" : "Manager",
  "contactNumber" : "+919999988822",
  "emailId" : "abc@test.com"
  }

Let us create a table named Employee which contains the data members same as node names in the above JSON payload and their corresponding getter and setter methods.

public class Employee {

	// private data members of POJO class
	private String firstName;
	private String lastName;
	private int age;
	private double salary;
	private String designation;
	private String contactNumber;
	private String emailId;

	// Getter and setter methods
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getContactNumber() {
		return contactNumber;
	}

	public void setContactNumber(String contactNumber) {
		this.contactNumber = contactNumber;
	}

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

We will convert a Java Object to a JSON object as a String and also will write it into a .json file. There are many variations for the method toJson().

You can create a Gson instance by invoking a new Gson() if the default configuration is all you need, as shown in the below example.

You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty-printing, custom JsonSerializer, JsonDeserializer.

public class EmployeeGsonTest {

	@Test
	public void gsonSerializationTest()  {

		// Create an object of POJO class
		Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");
		employee.setContactNumber("+919999988822");
		employee.setEmailId("abc@test.com");

		Gson gson = new Gson();
		String employeeJsonPayload = gson.toJson(employee);
		System.out.println(employeeJsonPayload);

		Gson builder = new GsonBuilder().setPrettyPrinting().create();
		String employeePrettyJsonPayload = builder.toJson(employee);
		System.out.println(employeePrettyJsonPayload);

	}
}

The execution message is shown below.

We can save this JSON payload as a file under our project or any location. Here, in the below example, will save the JSON payload under src/test/resources.

   @Test
	public void saveJsonToFile() {

	    Employee employee = new Employee();
		employee.setFirstName("Vibha");
		employee.setLastName("Singh");
		employee.setAge(30);
		employee.setSalary(75000);
		employee.setDesignation("Manager");
		employee.setContactNumber("+919999988822");
		employee.setEmailId("abc@test.com");

		Gson builder = new GsonBuilder().setPrettyPrinting().create();
		String employeePrettyJsonPayload = builder.toJson(employee);
		System.out.println(employeePrettyJsonPayload);

		String userDir = System.getProperty("user.dir");
		File outputJsonFile = new File(userDir + "\\src\\test\\resources\\EmployeePayloadUsingGson.json");
		try {
			FileWriter fileWriter = new FileWriter(outputJsonFile);
			builder.toJson(employee, fileWriter);
			fileWriter.flush();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

The JSON file is saved under src/test/resources as shown below image.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

Advertisement