Java
JSON
Pretty-Print
Programming
Code Formatting

Pretty-Print JSON in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Java, JSON (JavaScript Object Notation) is a lightweight data-interchange format, which is easy for humans to read and write, and easy for machines to parse and generate. JSON is commonly used for sending data between a server and a web application. However, when dealing with JSON data in raw form, it could become quite cumbersome due to its lack of formatting, making it hard to read and debug. This is where pretty-printing JSON becomes important.

Why Pretty-Print JSON?

Pretty-printing JSON transforms the compact, hard-to-read JSON string into a more readable and beautifully indented format. This is particularly beneficial during the development phase where developers need to easily inspect data, debug, and ensure the correct data structure is used. Moreover, for those who document their APIs or share JSON data samples, presenting them in a well-formatted manner increases readability and comprehensibility.

How to Pretty-Print JSON in Java

In Java, there are several ways to pretty-print JSON by using popular libraries such as org.json, Jackson, and Google Gson. Each of these libraries offers functionalities to serialize and deserialize JSON strings, along with utilities for pretty-printing.

Using Jackson

Jackson is one of the most popular libraries in the Java ecosystem for processing JSON. To pretty-print JSON using Jackson, you use the ObjectMapper class, which provides functionality to convert objects to JSON and vice-versa.

Here’s an example:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2import com.fasterxml.jackson.databind.SerializationFeature;
3
4public class JacksonExample {
5    public static void main(String[] args) throws Exception {
6        ObjectMapper mapper = new ObjectMapper();
7        mapper.enable(SerializationFeature.INDENT_OUTPUT);
8
9        Object yourObject = new Object();
10        // Convert your object to JSON string
11        String prettyJson = mapper.writeValueAsString(yourObject);
12
13        System.out.println(prettyJson);
14    }
15}

In this code, SerializationFeature.INDENT_OUTPUT is enabled on the ObjectMapper object to pretty-print the JSON output.

Using Gson

Google Gson is another popular library used for JSON parsing and serialization in Java. Gson provides easy-to-use mechanisms to convert Java objects into JSON and back.

Here’s a Gson pretty-print example:

java
1import com.google.gson.Gson;
2import com.google.gson.GsonBuilder;
3
4public class GsonExample {
5    public static void main(String[] args) {
6        Gson gson = new GsonBuilder().setPrettyPrinting().create();
7
8        Object yourObject = new Object();
9        // Convert your object to JSON string
10        String prettyJson = gson.toJson(yourObject);
11
12        System.out.println(prettyJson);
13    }
14}

In the Gson example, the GsonBuilder is used with the method setPrettyPrinting() to enable the pretty-print feature.

Comparison of Methods

Each method and library offers different features beyond just pretty-printing. Here is a brief comparison:

LibrarySetup RequiredFeature ControlCommunity and Support
JacksonMedium (dependencies and annotations may be needed)High (various configuration and features)Very High (widely used, lots of resources)
GsonLow (straightforward setup)Moderate (customization available but not as extensive as Jackson)High (popular and well-supported)

Additional Considerations

When choosing a library or method for handling JSON in Java, consider not only the pretty-print capabilities but also factors like performance, ease of integration, and the specific needs of your project. Each of these libraries also supports advanced features such as custom serializers, deserializers, and complex data bindings, which might be beneficial depending on your project requirements.

Conclusion

Pretty-printing JSON significantly enhances the readability of JSON data, making debugging and development processes more efficient. Choosing the right tool for JSON processing in Java depends on your project’s specific needs and the complexity of the JSON operations you intend to perform. Libraries like Jackson and Gson not only offer pretty-printing but also provide robust support for efficient JSON parsing and serialization.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.