How to convert Java object to / from JSON by (GSON)


GSON comes with simple JAVA API’s toJson()/fromJson() to convert JAVA object to/from JSON. Below is very simple example to convert Employee Java object to JSON and Vice versa. To know more about GSON follow the link GSON Introduction.

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

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

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		Gson gson = new Gson();
		<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println("Convert Java Object To JSON");
		System.out.println(json);

		System.out.println("Convert JSON To Java Object");
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set<Education> educationDetail;
private List<Experience> expericeDetail;

@Override
public String toString() {
	return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
			+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary + ", permanentAddress="
			+ permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile + ", educationDetail="
			+ educationDetail + ", expericeDetail=" + expericeDetail + "]";
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
		List<Experience> expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output:

Convert Java Object To JSON

{"employeeId":"C123","firstName":"Saurabh","middleName":"Kumar","lastName":"Gupta","designation":"Tech Lead","salary":50000,"permanentAddress":"Alpharetta,GA","mailingAddress":"Dallas, TX","mobile":"1231231230"}

Convert JSON To Java Object

Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is not formatted properly and not serialize null objects for education and experience. In next blog will explain about how to format JSON and serialize null values by using GsonBuilder.

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

Advertisements

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in GSON, JSON and tagged , , , . Bookmark the permalink.