How to convert object to JSON in java

To convert Java object to json we are using GSON jar and add to project class path. If you using web application then add to the lib directory.

Here download gson.jar from here gson.jar

package com.startwithjava
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;

class Employee{
public String name;
public double Salary;
public Employee(String name,double salary){
this.name=name;
this.salary=salary;
}
}
public class GsonTest {
public static void main(String[] args) {
Employee e= new Employee();
Gson gson = new Gson();

//Here object is converted to json string
String json = gson.toJson(e);

try {
//Define file name here for json.
FileWriter writer = new FileWriter("D:\\filename.json");
writer.write(json);
writer.close();

} catch (IOException e) {
e.printStackTrace();
}

System.out.println(json);

}
}

Leave a Reply