Over a million developers have joined DZone.

Grails Goodness: Pretty Print XML and JSON Output

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

If our Grails application renders XML or JSON output we can set configuration properties to enable pretty printing. This can be useful in for example in the development environment where we enable pretty printing and disable it for other environments. We set the configuration propertygrails.converters.default.pretty.print with the value true to enable pretty printing for both XML and JSON output. If we only want to pretty print XML we use the property grails.converters.xml.pretty.print and for JSON we usegrails.converters.json.pretty.print.

First we look at the XML and JSON output when we don't enable pretty printing for a simple book resource:

<?xml version="1.0" encoding="UTF-8"?><book id="1"><isbn>0451169514</isbn><numberOfPages>1104</numberOfPages><title>It</title></book>
{"class":"com.mrhaki.grails.sample.Book","id":1,"isbn":"0451169514","numberOfPages":1104,"title":"It"}

Now we get the same book resource but with the following grails-app/conf/Config.groovy snippet:

...
environments {
    development {
        // Enable pretty print for JSON.
        //grails.converters.json.pretty.print = true

        // Enable pretty print for XML.
        //grails.converters.xml.pretty.print = true

        // Enable pretty print for JSON and XML.
        grails.converters.default.pretty.print = true
        ...
    }
}        
...

The following output shows how the representation is formatted nicely:

<?xml version="1.0" encoding="UTF-8"?>
<book id="1">
  <isbn>
    0451169514
  </isbn>
  <numberOfPages>
    1104
  </numberOfPages>
  <title>
    It
  </title>
</book>
{
  "class": "com.mrhaki.grails.sample.Book",
  "id": 1,
  "isbn": "0451169514",
  "numberOfPages": 1104,
  "title": "It"
}

Code written with Grails 2.3.2.


The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}