How to convert Java object to JSON using GSON library?

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.

There are several Java libraries available to handle JSON objects. Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.

Converting Java object to JSON

The Google's Gson library provides a class with the same name (Gson) which is the main class of the library.

This class provides a method named toJson() there are several variants of this method where one among them accepts a Java object and converts it into a JSON object and returns it.

Therefore, to convert a Java object to a JSON String using GSON library −

  • Add the following maven dependency to your pom.xml

  • Create a javabean/POJO object with private variables and setter/getter methods.

  • Create another class (make sure that the POJO class is available to this).

  • In it, create an object of the POJO class, set required values to it using the setter methods.

  • Instantiate the Gson class.

  • Invoke the toJson() method by passing the above created POJO object.

  • Retrieve and print the obtained JSON.


class Student {
   private int id;
   private String name;
   private int age;
   private long phone;
   public int getId() {
      return id;
   public void setId(int id) { = id;
   public String getName() {
      return name;
   public void setName(String name) { = name;
   public int getAge() {
      return age;
   public void setAge(int age) {
      this.age = age;
   public long getPhone() {
      return phone;
   public void setPhone(long phone) { = phone;
public class ObjectTOString {
   public static void main(String args[]) {
      Student std = new Student();
      //Creating the Gson object
      Gson gSon = new Gson();
      String jsonString = gSon.toJson(std);



Updated on: 10-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started