JSON pretty print with JAX-RS/Jackson

If you have already worked with ElasticSearch, you may have used a very useful companion when dealing with your curl: the “?pretty” parameter which allows you to see the JSON response well-formated. If not, have a look here, you’ll thank me later: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/common-options.html

It can be usefull too to have this kind of feature in your JAX-RS project. And this is “pretty” simple (…). All you have to do is create a class extending JacksonJsonProvider:

import java.io.IOException;
import java.io.OutputStream;

import javax.ws.rs.core.Context;

import org.apache.cxf.jaxrs.ext.MessageContext;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

public class PrettyJacksonJsonProvider extends JacksonJsonProvider {

  private MessageContext mc;

  public PrettyJacksonJsonProvider(ObjectMapper mapper) {

 public void setMessageContext(MessageContext context) {
  this.mc = context;

 protected JsonGenerator _createGenerator(ObjectWriter writer, OutputStream rawStream, JsonEncoding enc) throws IOException {
  JsonGenerator generator = super._createGenerator(writer, rawStream, enc);

   String pretty = mc.getHttpServletRequest().getParameter("pretty");

   if (pretty != null && ("".equals(pretty) || "true".equals(pretty))) {

   return generator;

Then, replace your previous JacksonJsonProvider by this one, start your server and enjoy the “?pretty” !

Related Posts

Comments (1)

Leave a comment

About privacy:

This site uses Akismet to reduce spam. Learn how your comment data is processed.