A Gson เป็นไลบรารี JSON สำหรับจาวาซึ่งสร้างโดย Google โดยใช้ Gson เราสามารถ สร้าง JSON และแปลง JSON เป็นวัตถุ java โดยค่าเริ่มต้น Gson สามารถพิมพ์ JSON ในรูปแบบกะทัดรัด . เพื่อเปิดใช้งาน Gson สวยพิมพ์ เราต้องกำหนดค่าอินสแตนซ์ Gson โดยใช้ setPrettyPrinting() วิธีการของ GsonBuilder คลาสและวิธีนี้กำหนดค่า Gson ให้ส่งออก JSON ที่เหมาะกับหน้าสำหรับการพิมพ์ที่สวยงาม
ไวยากรณ์
public GsonBuilder setPrettyPrinting()
ตัวอย่าง
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);
}
}
// Employee class
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;
}
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;
}
} ผลลัพธ์
{
"name": "Raja",
"id": "115",
"designation": "Content Engineer",
"technology": "Java",
"location": "Hyderabad"
}