在Java中使用Gson库将Java对象转换为JSON?

在Java中使用Gson库将Java对象转换为JSON?

Gson 是一个由 Google 创建的用于 Java 的 json 库,它可以用来生成 JSON。通过使用 Gson,我们可以生成 JSON 并将一个 bean/ java 对象转换为 JSON 对象。我们可以调用 Gson 类的 toJson() 方法将 Java 对象转换为 JSON 对象。

语法

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

示例

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

输出

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

以上就是在Java中使用Gson库将Java对象转换为JSON?的详细内容,更多请关注其它相关文章!