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) {
  super(mapper);
 }

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

  @Override
 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))) {
   generator.useDefaultPrettyPrinter();
  }

   return generator;
 }
}

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

Related Posts

Comments (1)

Leave a comment