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

Convert Java objects to JSON using Gson library in Java?

WBOY
Release: 2023-09-09 14:09:02
forward
1201 people have browsed it

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)
Copy after login

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 +
               " ]";
   }
}
Copy after login

Output

{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template