Convert Object to JSON using GSON
In this tutorial, I am attaching simple program flow about How to Convert Object to JSON using GSON API. The example program were shared in the same post.
Employee.java
package com.dineshkrish.gson; public class Employee { private int employeeId; private String employeeName; private int employeeAge; private String employeeGender; private String employeeAddress; public int getemployeeId() { return employeeId; } public void setemployeeId(int employeeId) { this.employeeId = employeeId; } public String getemployeeName() { return employeeName; } public void setemployeeName(String employeeName) { this.employeeName = employeeName; } public int getemployeeAge() { return employeeAge; } public void setemployeeAge(int employeeAge) { this.employeeAge = employeeAge; } public String getemployeeGender() { return employeeGender; } public void setemployeeGender(String employeeGender) { this.employeeGender = employeeGender; } public String getemployeeAddress() { return employeeAddress; } public void setemployeeAddress(String employeeAddress) { this.employeeAddress = employeeAddress; } }
ObjectToJSON.java
package com.dineshkrish.gson; import java.io.File; import java.io.FileWriter; import java.io.IOException; import com.google.gson.Gson; public class ObjectToJSON { public static void main(String[] args) { // Defining Gson Object Gson gson = new Gson(); // Creating File Object for output JSON file File outputJsonFile = new File("employee.json"); // FileWrite to write Json data on file FileWriter fw = null; // Defining Employee Object Employee employee = new Employee(); employee.setemployeeId(1001); employee.setemployeeName("Dinesh Krishnan"); employee.setemployeeAge(30); employee.setemployeeGender("Male"); employee.setemployeeAddress("India"); try { fw = new FileWriter(outputJsonFile); // Covert Object to JSON using GSON API gson.toJson(employee, fw); fw.close(); System.out.println("Converted Successfully..."); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
Output
——————
Converted Successfully…
employee.json
{“employeeId”:1001,”employeeName”:”Dinesh Krishnan”,”employeeAge”:30,”employeeGender”:”Male”,”employeeAddress”:”India”}
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet