JSON
Pretty Print
Jackson Library
Java
Data Formatting

Convert JSON String to Pretty Print JSON output using Jackson

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

JSON (JavaScript Object Notation) is a lightweight format commonly used for data interchange. While JSON remains readable in its raw form, a pretty-printed JSON enhances readability by introducing indents and line breaks. Jackson, a powerful library for processing JSON in Java, provides an efficient way to convert a JSON string into a pretty-printed format. This article delves into using the Jackson library for transforming JSON strings into a visually structured layout with methods, examples, and useful insights.

Understanding Jackson Library

Jackson is a suite of data-processing tools for Java, offering a comprehensive suite to parse, transform, and map data in JSON format. With its streaming API, data-binding, and powerful annotations, Jackson is an increasingly popular choice for JSON handling.

Maven Dependency

To use Jackson in your Java project, you need to add the following dependencies to your Maven pom.xml:

xml
1<dependency>
2    <groupId>com.fasterxml.jackson.core</groupId>
3    <artifactId>jackson-databind</artifactId>
4    <version>2.12.3</version>
5</dependency>

Jackson's Core Components

  1. ObjectMapper: The primary class used for converting data between JSON and Java objects.
  2. JsonFactory: A low-level, JSON token-based parser and generator.
  3. JsonNode: A node-based representation of JSON tree structure.

Converting JSON String to Pretty Print JSON

Converting a JSON string into a pretty-printed format involves parsing the string and applying the desired formatting. The ObjectMapper class from Jackson offers methods to facilitate this transformation.

Example

Below is a simple Java example demonstrating how to convert a JSON string to a pretty-printed JSON using Jackson.

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2import com.fasterxml.jackson.databind.ObjectWriter;
3import com.fasterxml.jackson.core.JsonProcessingException;
4
5public class JsonPrettyPrinter {
6
7    public static void main(String[] args) {
8        String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
9        
10        try {
11            prettyPrintJson(jsonString);
12        } catch (JsonProcessingException e) {
13            e.printStackTrace();
14        }
15    }
16
17    public static void prettyPrintJson(String jsonString) throws JsonProcessingException {
18        ObjectMapper mapper = new ObjectMapper();
19        Object json = mapper.readValue(jsonString, Object.class);
20        
21        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
22        String prettyJson = writer.writeValueAsString(json);
23        
24        System.out.println(prettyJson);
25    }
26}

Explanation

  • ObjectMapper: First, an ObjectMapper instance is created to handle JSON data.
  • readValue(): This method reads a JSON content from the provided JSON string and deserializes it into a generic Java Object.
  • ObjectWriter and writerWithDefaultPrettyPrinter:
    • ObjectWriter provides various writing capabilities.
    • writerWithDefaultPrettyPrinter() configures the writer for pretty printing using default settings.
  • writeValueAsString(): This method serializes the Java object back into a JSON string. Since we configured the writer with pretty printing, the output is nicely formatted.

Practical Use Cases

Pretty printing JSON data is especially useful in situations such as:

  • Debugging JSON content during development.
  • Logging JSON data in a structured format.
  • Exporting JSON for documentation purposes.

Comparison Table

Here's a summarized comparison between plain and pretty-printed JSON output:

AspectPlain JSONPretty JSON
ReadabilityHard to readEasy to read with indents
Uses in DebuggingChallenging to parseSimple and clear
Character LengthMinimalIncreased due to whitespace
Human-FriendlyNoYes

Optimization Tips

  • Conditional Pretty Printing: Only apply pretty printing in development or debugging environments to avoid unnecessary data transfer overhead.
  • Customization: Use custom pretty printers in Jackson to control indent styles and other formatting preferences.

Conclusion

Leveraging Jackson for JSON processing and pretty-printing significantly enhances the readability of JSON data. The provided examples and explanations about essential Jackson components demonstrate how straightforward and powerful JSON transformation can be in Java applications. Trusting Jackson's capabilities ensures streamlined and efficient JSON handling tailored to various application needs.

Understanding Jackson's rich set of features allows developers to fine-tune JSON operations, making it an indispensable tool in any Java developer's toolkit.


Course illustration
Course illustration

All Rights Reserved.