Pretty printing JSON from Jackson 2.2's ObjectMapper
To get a JSON beauty makeover in Jackson, just configure your ObjectMapper
like this:
Turn on INDENT_OUTPUT
to beautify your JSON by adding necessary whitespace. Swap out yourObject
with your actual object to be serialized.
Detailed Configuration
String Refactoring
Let's say you have an ugly duckling String
containing JSON and you want it to become a beautiful swan. Use the writerWithDefaultPrettyPrinter
method:
Writing to Files
You can write your beautified JSON directly to a file, like keeping a photograph of your object's best look:
Gson: The Alternative
If you don't mind trying on a new fashion with Gson, here's how it offers pretty printing:
From File to Fancy
Here's how to read a Plain Jane JSON file and transform it into a prom queen pretty-printed JSON String
:
Deep Dive into ObjectMapper
Playing Safe
While working with ObjectMapper
, remember those good manners:
- Your classes need proper getters and setters.
- Handle the exceptions that may feel like party crashers.
Set the Tone
You can add your personal touch with custom indentation. More like choosing the music for your JSON party:
Power of Parsing
ObjectMapper
is powerful. It not only writes but reads JSON bravely:
It's versatile and can parse from Strings, Files, Streams and more.
Console Output
For that quick photo snap or to showoff your pretty JSON, print it to the console:
Ensure you dance with the right version of Jackson for your pretty printing moves.
Was this article helpful?