Java Jackson – Pretty Print JSON Output Example

1. Introduction

Jackson is a powerful Java library used for processing JSON data. A common requirement while working with JSON is to have a nicely formatted, human-readable output. Jackson's ObjectMapper class offers a way to pretty print JSON data, which makes it easier to read and debug.

2. Example Steps

1. Add the Jackson library dependencies to your project.

2. Create a sample Java object or structure that you want to convert to pretty-printed JSON.

3. Use Jackson's ObjectMapper class to serialize the Java object and enable the pretty-print feature.

4. Output the prettily formatted JSON to the console.

3. Pretty Print JSON Output Example

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonPrettyPrintExample {

    public static void main(String[] args) {
        // Sample Java object.
        Person person = new Person("John", "Doe", 30);

        try {
            // Initialize ObjectMapper instance.
            ObjectMapper objectMapper = new ObjectMapper();

            // Enable pretty print feature.
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

            // Convert Java object to pretty printed JSON string.
            String prettyJson = objectMapper.writeValueAsString(person);

            // Print out the pretty printed JSON string.
            System.out.println(prettyJson);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    static class Person {
        private String firstName;
        private String lastName;
        private int age;

        public Person(String firstName, String lastName, int age) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
        }

        // Getters and setters...
    }
}

Output:

{
  "firstName" : "John",
  "lastName" : "Doe",
  "age" : 30
}

4. Step By Step Explanation

1. We begin by defining a simple Java Person object with attributes like firstName, lastName, and age.

2. We then initialize Jackson's ObjectMapper, which is responsible for the conversion between Java objects and their JSON representation.

3. To enable pretty printing, we invoke the enable method on the ObjectMapper instance and pass SerializationFeature.INDENT_OUTPUT as the argument. This feature makes sure that the generated JSON is in a human-readable format.

4. The writeValueAsString method of the ObjectMapper is then used to convert our Person object into a JSON string. Due to the enabled pretty print feature, the resultant JSON string is formatted with proper indentation and line breaks.

5. Finally, we print out the prettily formatted JSON string to the console, which confirms the pretty-printing functionality.


Comments