
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pretty Print JSON Using Gson Library in Java
JSON is a data interchange format that is easy to read and write. It is lightweight and gets parsed easily. It is commonly used in web applications for sending and receiving data. To know more about JSON, refer to JSON.
Pretty print is a type of formatting that formats data in a more easily readable way by adding indentation and line breaks. It is useful for debugging and logging purposes.
Enabling pretty print Using Gson Library
Gson is a JSON library for Java, which was created by Google. By using Gson, we can generate JSON and convert JSON to Java objects. By default, Gson can print the JSON in a compact format.
To enable Gson pretty print, we must configure the Gson instance using the setPrettyPrinting() method of the GsonBuilder class, and this method configures Gson to output JSON that fits on a page for pretty printing.
Let's see how to pretty print JSON using the Gson library:
- First, we need to add the Gson library to our project. If you are using Maven, add this to your
pom.xml
file:<dependency> <groupId>com.google.code.gson< ;/groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
- If you do not use Maven, add a jar file to your project. You can download the jar file from here.
- Then create a JSON object.
- Then we will create an instance of the Gson class.
- Next, we will convert the JSON object to a pretty-print JSON string using the setPrettyPrinting() method of GsonBuilder.
- Finally, we will print the pretty-print JSON string.
Example
The following is the code to pretty print JSON using the Gson library:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class PrettyPrintJson { public static void main(String[] args) { // Create a JSON object String json = """ { "name": "Ansh", "age": 23, "isSelfEmployee": false, "salary": 10000000.00, "address": { "city": "Delhi", "state": "Delhi" }, "skills": ["Java", "Python", "JavaScript"] } """; // Create a Gson instance Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Convert the JSON object to pretty print JSON string String prettyJson = gson.toJson(JsonParser.parseString(json)); // Print the pretty print JSON string System.out.println(prettyJson); } }
Output
Following is the output of the above code:
{ "name": "Ansh", "age": 23, "isSelfEmployee": false, "salary": 10000000.0, "address": { "city": "Delhi", "state": "Delhi" }, "skills": [ "Java", "Python", "JavaScript" ] }