Gson là thư viện cho Java dùng để tạo JSON. Ta dùng phương thức fromJson() của Gson để parse chuỗi JSON thành đối tượng Java và dùng toJson() của Gson để chuyển đối tượng Java thành chuỗi JSON.
Phương thức fromJson() có 2 tham số: tham số đầu là chuỗi JSON cần parse, tham số hai là lớp Java để parse vào. Phương thức toJson() nhận 1 tham số là đối tượng Java cần chuyển thành chuỗi JSON.
Cú pháp fromJson()
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
Ví dụ fromJson()
import com.google.gson.*;
public class FromJsonMethodTest {
public static void main(String[] args) {
String jsonString = "{'id':101, 'firstName':'Jai','lastName':'Adithya'}";
Gson gson = new Gson();
Employee emp = gson.fromJson(jsonString, Employee.class);
System.out.println(emp);
}
}
// Lớp Employee
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();
}
}
Kết quả fromJson()
Id : 101, FirstName : Jai, Last Name : Adithya
Cú pháp toJson()
public java.lang.String toJson(java.lang.Object src)
Ví dụ toJson()
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);
}
}
// Lớp Employee (giống ví dụ trên)
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; }
}
Kết quả toJson()
{"id":110,"firstName":"Raja","lastName":"Ramesh"}
Tóm tắt: toJson() = Serialize (Object → JSON), fromJson() = Deserialize (JSON → Object).