Gson là thư viện JSON cho Java, do Google tạo. Bằng Gson, có thể generate JSON và chuyển JSON sang object Java. Mặc định Gson in JSON ở compact format. Để bật Gson pretty print, phải cấu hình instance Gson dùng phương thức setPrettyPrinting() của GsonBuilder, method này cấu hình Gson output JSON fit trong trang để pretty print.
Cú pháp
public GsonBuilder setPrettyPrinting()
Ví dụ minh họa
import java.util.*;
import com.google.gson.*;
public class PrettyJSONTest {
public static void main(String[] args) {
Employee emp = new Employee("Raja", "115", "Content Engineer", "Java", "Hyderabad");
Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
String prettyJson = gson.toJson(emp);
System.out.println(prettyJson);
}
}
// Lớp Employee
class Employee {
private String name, id, designation, technology, location;
public Employee(String name, String id, String designation, String technology, String location) {
super();
this.name = name;
this.id = id;
this.designation = designation;
this.technology = technology;
this.location = location;
}
// getters...
public String getName() { return name; }
public String getId() { return id; }
public String getDesignation() { return designation; }
public String getTechnology() { return technology; }
public String getLocation() { return location; }
}
Kết quả
{
"name": "Raja",
"id": "115",
"designation": "Content Engineer",
"technology": "Java",
"location": "Hyderabad"
}
So sánh: Compact: {"name":"Raja","id":"115",...}. Pretty: có indentation và line break. Pretty print hữu ích cho debug, log, config file. Production API thường dùng compact để tiết kiệm bandwidth.