Convert Java object to JSON using the Gson library in Java?

JavaJSONObject Oriented ProgrammingProgramming

A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert a bean/ java object to a JSON object. We can call the toJson() method of Gson class to convert a Java object to a JSON object.

Syntax

public java.lang.String toJson(java.lang.Object src)

Example

import com.google.gson.Gson;
public class ConvertJavaObjectToJSONTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      Student student = new Student("Raja", "Ramesh", 30, "Hyderabad");
      System.out.println(gson.toJson(student)); // converts java object to json object.
   }
}
// student class
class Student {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Student(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String toString() {
      return "Student[ " +
               " firstName = " + firstName +
               ", lastName = " + lastName +
               ", age = " + age +
               ", address = " + address +
               " ]";
   }
}

Output

{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
raja
Published on 23-Sep-2019 13:22:49
Advertisements