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.

employee.json


{"id":1,"name":"employee1","ssn":1234}

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) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.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 java.io.File;
2  import java.io.FileReader;
3  import java.io.IOException;
4  
5  import com.google.gson.Gson;
6  
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

Output

Id:1
Name:employee1
ssn: 1234

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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