Serializing Java objects to JSON

In this post under Gson. I will show how to serialize a java object to JSON using Gson framework.

Below is the complete code.

Main Code


1  import java.io.File;
2  import java.io.FileWriter;
3  import java.io.IOException;
4  
5  import com.google.gson.Gson;
6  
7  public class GsonDemo1 {
8   public static void main(String[] args) {
9       Employee employee = new Employee();
10      employee.setId(1);
11      employee.setName("employee1");
12      employee.setSsn(1234);
13      
14      Gson gson = new Gson();
15      File file = new File("employee.json");
16      try (FileWriter fw = new FileWriter(file);) {
17          gson.toJson(employee, fw);
18      } catch(IOException excep) {
19          excep.printStackTrace();
20      }
21  }
22 }

At line 9, I create an instance of Employee instance.

At line 14, I create an instance of Gson class with default configurations.

At line 17, we serialize the employee instance by calling toJson method. This method requires two arguments
1) the object to be serialized
2) the writer object

The above code will create a file named “employee.json” and store the JSON representation of the object in the file.


Check these products on Amazon
Advertisements

Leave a Reply