JSON Pretty Printing with JSON Processing API

In this example, we create a simple JSON object and pretty print to the console using JSON-P library.


The code example is available at my Github repository.
Check out complete JSON-P tutorial at Java JSON Processing Tutorial.

JSON Pretty Printing Example

With JsonGenerator.PRETTY_PRINTING configuration setting, we can set the writer for pretty printing. In the example, we create a JSON object and print it to the console. The output is pretty-printed.
package net.javaguides.jsonp.examples;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.json.JsonWriterFactory;
import javax.json.stream.JsonGenerator;
import java.io.StringWriter;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

public class JsonPrettyPrintExample {
    public static void main(String[] args) {

        String postedDate = LocalDate.of(2019, 7, 15).toString();

        JsonObject json = Json.createObjectBuilder()
            .add("id", "100")
            .add("title", "JSON-Processing API Post")
            .add("description", "JSON-Processing API Post")
            .add("postedDate", postedDate).build();

        Map < String, Boolean > config = new HashMap < String, Boolean > ();
        config.put(JsonGenerator.PRETTY_PRINTING, true);

        JsonWriterFactory jwf = Json.createWriterFactory(config);
        StringWriter sw = new StringWriter();

        try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
            jsonWriter.writeObject(json);
            System.out.println(sw.toString());
        }
    }
}
Output:

{
    "id": "100",
    "title": "JSON-Processing API Post",
    "description": "JSON-Processing API Post",
    "postedDate": "2019-07-15"
}
Let's understand the above example.
Created a simple JSON object:
JsonObject json = Json.createObjectBuilder()
.add("id", "100")
.add("title", "JSON-Processing API Post")
.add("description", "JSON-Processing API Post")
.add("postedDate", postedDate).build();
The configuration file is passed to the JsonWriterFactory and use JsonWriter to write JSON to console:
Map<String, Boolean> config = new HashMap<String, Boolean>();
config.put(JsonGenerator.PRETTY_PRINTING, true);

JsonWriterFactory jwf = Json.createWriterFactory(config);
StringWriter sw = new StringWriter();

try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
	jsonWriter.writeObject(json);
	System.out.println(sw.toString());
}

Comments