Deserializing JSON to Java Object

In this post under Gson. I will show how to deserialize a JSON data back to Java object using Gson framework.

For our example I will use the below json data. The json data contains employee information.



The class structure of Employee is as shown below

Employee class

public class Employee {
    private int id;
    private String name;
    private int ssn;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getSsn() {
        return ssn;

    public void setSsn(int ssn) {
        this.ssn = ssn;
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Id:" + id).append("\n");
        sb.append("Name:" + name).append("\n");
        sb.append("ssn: " + ssn);
        return sb.toString();

Below is the complete code

Main Code

1  import;
2  import;
3  import;
5  import;
7  public class GsonDemo2 {
8   public static void main(String[] args) {
9       File file = new File("employee.json");
10      Gson gson = new Gson();
11      try (FileReader fr = new FileReader(file)) {
12          Employee employee = gson.fromJson(fr, Employee.class);
13          System.out.println(employee);
14      } catch (IOException excep) {
15          excep.printStackTrace();
16      }
17  }
18 }

At line 9, I create a file object representing the file “employee.json”.

At line 10, I create a Gson instance “gson”.

At line 12, I deserialize the content in employee.json file to employee object by calling “fromJson” mehtod.

It takes two arguments
1) the FileReader object to read the file
2) the target class type


ssn: 1234


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s