Gson是一個用於Java的函式庫,可以用來產生JSON。我們可以使用Gson的fromJson()方法將JSON字串解析為Java對象,並使用Gson的toJson()方法將Java對象轉換為JSON字串。 fromJson()方法有兩個參數,第一個參數是要解析的JSON字串,第二個參數是要解析的Java類別。我們可以將一個參數傳遞給toJson()方法,也就是我們要轉換為JSON字串的Java物件。
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
import com.google.gson.*; public class FromJsonMethodTest { public static void main(String[] args) { String jsonString = "{'id':101, 'firstName':'Jai','lastName':'Adithya'}"; <strong>Gson </strong>gson = new Gson(); Employee emp = gson.fromJson(jsonString, Employee.class); System.out.println(emp); } } // Employee class<strong> </strong>class Employee { private int id; private String firstName; private String lastName; public Employee() {} public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Id : " + id); sb.append(", FirstName : " + firstName); sb.append(", Last Name : " + lastName); return sb.toString(); } }
Id : 101, FirstName : Jai, Last Name : Adithya<strong> </strong>
public java.lang.String toJson(java.lang.Object src)
import com.google.gson.*; public class ToJsonMethodTest { public static void main(String[] args) { Employee emp = new Employee(); emp.setId(110); emp.setFirstName("Raja"); emp.setLastName("Ramesh"); Gson gson = new Gson(); String jsonString = gson.toJson(emp); System.out.println(jsonString); } } // Employee class<strong> </strong>class Employee { private int id; private String firstName; private String lastName; public Employee() {} public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } }
{"id":110,"firstName":"Raja","lastName":"Ramesh"}
以上是Gson在Java中的fromJson()和toJson()方法之間的差異是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!