Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Pretty Print JSON ด้วย Gson Library ใน Java

Gson เป็น JSON Library สำหรับ Java สร้างโดย Google Generate JSON และแปลง JSON → Java Objects โดย Default Gson Print JSON แบบ Compact Format เพื่อ Enable Gson Pretty Print ต้อง Config Gson Instance ด้วยเมธอด setPrettyPrinting() ของ GsonBuilder เมธอดนี้ตั้งค่า Gson ให้ Output JSON ที่วางในหน้าได้สวยงาม

Syntax

public GsonBuilder setPrettyPrinting()

ตัวอย่าง: Pretty Print JSON

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) {
        this.name = name;
        this.id = id;
        this.designation = designation;
        this.technology = technology;
        this.location = location;
    }
    
    // Getters...
}

ผลลัพธ์

{
  "name": "Raja",
  "id": "115",
  "designation": "Content Engineer",
  "technology": "Java",
  "location": "Hyderabad"
}

เปรียบเทียบ:

  • Compact (Default): {"name":"Raja","id":"115","designation":"Content Engineer","technology":"Java","location":"Hyderabad"}
  • Pretty Print: 2-Space Indent, New Lines, Readable

ใช้เมื่อ: Debug, Logging, Config Files, Human-readable Output