in Java when i use the
@Produces("application/json")
annotation the output is not formated into human readable form. How do i achive that?
We add the setPrettyPrinting() method to the GsonBuilder object to enable pretty-printing of JSON while constructing the Gson object. To use the Gson library, add the Gson dependency from the Maven Repository.
We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.
Chances are that if you use JAX-RS 2.0 or 2.1 in Open Liberty, then you use JSON to format your data. If so, it's equally likely that you use Jackson as your JSON provider. Open Liberty's JAX-RS 2.0 implementation uses Jackson as its default JSON provider.
Just for the record, if you want to enable the pretty output only for some resources you can use the @JacksonFeatures annotation on a resource method.
Here is example:
@Produces(MediaType.APPLICATION_JSON)
@JacksonFeatures(serializationEnable = { SerializationFeature.INDENT_OUTPUT })
public Bean resource() {
return new Bean();
}
This is how you can properly do conditional pretty/non-pretty json output based on presence of "pretty" in query string.
Create a PrettyFilter
that implements ContainerResponseFilter
, that will be executed on every request:
@Provider
public class PrettyFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext reqCtx, ContainerResponseContext respCtx) throws IOException {
UriInfo uriInfo = reqCtx.getUriInfo();
//log.info("prettyFilter: "+uriInfo.getPath());
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
if(queryParameters.containsKey("pretty")) {
ObjectWriterInjector.set(new IndentingModifier(true));
}
}
public static class IndentingModifier extends ObjectWriterModifier {
private final boolean indent;
public IndentingModifier(boolean indent) {
this.indent = indent;
}
@Override
public ObjectWriter modify(EndpointConfigBase<?> endpointConfigBase, MultivaluedMap<String, Object> multivaluedMap, Object o, ObjectWriter objectWriter, JsonGenerator jsonGenerator) throws IOException {
if(indent) jsonGenerator.useDefaultPrettyPrinter();
return objectWriter;
}
}
}
And pretty much that's it!
You will need to ensure that this class gets used by Jersey by either automated package scanning or registered manually.
Spent few hours trying to achieve that and found that no-one has published a ready-to-use solution before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With