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

javajsonobject oriented programmingprogramming

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) {
      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 classclass 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"}

相关文章