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

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.5</version>
</dependency>
  • 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.

Example

import com.google.gson.Gson;
class Student {
   private int id;
   private String name;
   private int age;
   private long phone;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.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) {
      this.phone = phone;
   }
}
public class ObjectTOString {
   public static void main(String args[]) {
      Student std = new Student();
      std.setId(001);
      std.setName("Krishna");
      std.setAge(30);
      std.setPhone(9848022338L);
      //Creating the Gson object
      Gson gSon = new Gson();
      String jsonString = gSon.toJson(std);
      System.out.println(jsonString);
   }
}

Output

{"id":1,"name":"Krishna","age":30,"phone":9848022338}

Updated on: 10-Oct-2019

959 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements