How to pretty print a JsonObject using Jakarta EE API

This tutorial wil teach you how to pretty print a JsonObject using javax.json API which is part of Jakarta EE / Java EE API.

By default if you run a toString() of a javax.json.JsonObject a rough output will be displayed with no formatting. By setting the property JsonGenerator.PRETTY_PRINTING into the JsonGeneratorFactory you will have a nicely formatted Json output.

See this example:

JsonReader jsonReader = Json.createReader(this.getClass().getClassLoader().getResourceAsStream("data.json"));
obj = jsonReader.readObject();

Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
StringWriter sw = new StringWriter();
JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
JsonWriter jsonWriter = writerFactory.createWriter(sw);

jsonWriter.writeObject(obj);
jsonWriter.close();
System.out.println(sw.toString());

On the other hand, if you are using Google’s Gson object, you can do it in a simple statement:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Which requires in your pom.xml:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>