Home  >  Article  >  Java  >  Convert Java objects to JSON using Gson library in Java?

Convert Java objects to JSON using Gson library in Java?

WBOY
WBOYforward
2023-09-09 14:09:021196browse

Convert Java objects to JSON using Gson library in Java?

#Gson is a json library for Java created by Google that can be used to generate 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 the Gson class to convert a Java object into 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) {
      <strong>Gson </strong>gson = new Gson();
      Student student = new Student("Raja", "Ramesh", 30, "Hyderabad");
      System.out.println(gson<strong>.toJson(student)); </strong><strong>// converts java object to json object.</strong>
   }
}
// student class<strong>
</strong>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"}

The above is the detailed content of Convert Java objects to JSON using Gson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete