I'm trying to configure my Jax RS application in WebSphere Portal 8.5 I need to output application/json media type in pretty print format.
I've read some documentation and createad a Context Resolver:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JaxRsContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper objectMapper;
public JaxRsContextResolver() {
System.out.println("JaxRsContextResolver is executed");
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
objectMapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true);
objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
}
@Override
public ObjectMapper getContext(Class<?> objectType) {
return objectMapper;
}
}
Unfortunately even if the system out is printed, the configuration is not used
Hi. Pretty Print, as in the Jackson Pretty Print? Or something else? Are you using Jackson 2.0 and above? -Brian
With pretty print I mean the output formatted with tabs and newlines for each property. I don't know which jackson I'm using because it's bundled with WebSphere Portal 8.5 so I don't add any additional JAR
Answer by nchieffo (85) | May 19, 2016 at 05:20 AM
This code is the solution to my problem
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JaxRsMessageBodyWriterConfiguration implements MessageBodyWriter<Object> {
@Override
public long getSize(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
return -1;
}
@Override
public void writeTo(Object obj, Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream os) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
objectMapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true);
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
objectMapper.writeValue(os, obj);
}
@Override
public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
}
Does WAS Liberty Profile support @Singleton resource annotations? 3 Answers
Liberty API-Discovery uses which version of Swagger? 2 Answers
Liberty jaxrs-2.0 fails to marshal JAXB objects containing List to JSON. 2 Answers
I am facing problem in File Upload service using JAX-RS 2.1 with websphere liberty 8.5.5 0 Answers
org.apache.wink.client.internal.BaseRequestResponse cannot be resolved 7 Answers