Jackson ObjectMapper to pretty print Json string

August 19, 2017
Tags: » json » jackson ObjectMapper » html

A couple weeks ago I used the Jackson ObjectMapper to convert an object into Json string to put in an email, like so:

ObjectMapper objectMapper = new ObjectMapper()
String jsonStr = objectMapper.writeValueAsString(myObject)

While it did work turning the object into a Json string, it looked like this in the email:
flat json string

It worked, BUT I wanted to make it stand up for readability, you know, like all the pretty Json strings you see on the Internet.

To make that work, I did something like this:

String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(myObject)

It somehow didn’t make the Json string stand up in my email.

To test if the code worked at all, I printed the string out in the terminal. And it looked perfect in the terminal:
terminal json string

So something else was causing the pretty print not working in the email. Could it be the HTML code that I wrapped the Json string in?

String emailContent = "<html><body><h4>Client Detail:</h4><p>$jsonStr</p></body></html>"

After some research and experiment, I replaced the <p> tag with the <pre> tag, like so:

<pre>$jsonStr</pre>

And then some miracle happened. The Json string stood up with pride in the email:
stand json string

But WHY? According to the w3c documentation:

The PRE element tells visual user agents that the enclosed text is “preformatted”. When handling preformatted text, visual user agents:

Ha!

♥ Hi there, do you know you can also leave a comment as a guest?
When you click the Name text box, more content will show up. Check I'd rather post as a guest at the bottom of the text boxes, then you're good to go!