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?的詳細內容。更多資訊請關注PHP中文網其他相關文章!