Reputation: 31
I've come across "best practices" sites that mention that your should pretty print your JSON output from your RESTful web services. I am finding a lot of resources for how to pretty print JSON in general, but as I am letting JBoss (and RESTEasy) output my JSON behind the covers, I don't know of any way to tweak what it serves.
My code looks something like:
@GET
@Path("books")
@Produces({ MediaType.APPLICATION_JSON })
public Book getBooks() {
return doGetBooks();
}
JBoss handles the requests and builds the JSON just fine, but its compacted. I haven't yet found any way to tell JBoss to pretty print it so its more human readable in a browser and such. I've found some documentation on how to pretty print XML served from JBoss, just not JSON.
Thanks guys!
Upvotes: 3
Views: 1874
Reputation: 5468
I have a bit of a round about solution that prints it pretty decently. (Not the best Pretty Print but it is enough)
You'll need the following from Maven:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Then you can change your method to something like this:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
...
private final ObjectWriter WRITER = new ObjectMapper().writerWithDefaultPrettyPrinter();
...
@GET
@Path("books")
@Produces({ MediaType.APPLICATION_JSON })
public Response getBooks() {
return Response.status(Status.OK).entity(WRITER.writeValueAsString(doGetBooks())).build();
}
Since what it does is:
Response
object with a 200
Response Code with the JSON String
.Edit: it might be wise to make this available by a adding a query param like pretty=true
since it would increase your response output size.
You can also look at this: http://docs.jboss.org/resteasy/2.0.0.GA/userguide/html/Built_in_JAXB_providers.html#decorators which describes creating a XML decorator which you may be able to adapt for JSON to still return objects and make it behind the scenes. (I'll try to fiddle with this later)
Upvotes: 4