Gson Java के लिए एक JSON लाइब्रेरी है, जिसे Google द्वारा बनाया गया है। Gson का उपयोग करके, हम JSON उत्पन्न कर सकते हैं और JSON को Java ऑब्जेक्ट्स में बदल सकते हैं। डिफ़ॉल्ट रूप से, Gson JSON को कॉम्पैक्ट फॉर्मेट में प्रिंट कर सकता है। Gson प्रिटी प्रिंट सक्षम करने के लिए, हमें GsonBuilder क्लास के setPrettyPrinting() मेथड का उपयोग करके Gson इंस्टेंस को कॉन्फ़िगर करना होगा और यह मेथड 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(); // प्रिटी प्रिंट
String prettyJson = gson.toJson(emp);
System.out.println(prettyJson);
}
}
// 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;
}
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"
}