Friday, 16 December 2016

Java Object to JSON Conversion Using Gson

Employee.java

public class Employee {

    private int empId;
    private String name;
    private String designation;
    private String department;
    private int salary;
   
    public int getEmpId() {
        return empId;
    }
    public void setEmpId(int empId) {
        this.empId = empId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
}

ObjectToJson.java

import java.io.FileWriter;
import java.io.IOException;

import com.google.gson.Gson;

public class ObjectToJsonEx {

    public static void main(String a[]){
       
        Employee emp = new Employee();
        emp.setEmpId(007);
        emp.setName("Sivasankar T");
        emp.setSalary(10000);
        emp.setDesignation("Analyst Programmer");
        emp.setDepartment("Development");
       
        Gson gsonObj = new Gson();
        try
        {

FileWriter file = new FileWriter("./Employee.json");
   file.write(gsonObj.toJson(emp));
   file.flush();
   file.close();

   }
        catch (IOException e)
        {
e.printStackTrace();
  }
       
System.out.print(gsonObj);

    }
}

Output:

{

"empId":1016,
"name":"Sivasankar T",
"designation":"Manager",
"department":"Accounts",
"salary":20000
}


No comments:

Post a Comment