I use @JsonFilter to selectively filter out properties on the same object, Spring didn't (and still doesn't?) support this at the time, so I registered a custom MappingJackson2HttpMessageConverter which inspects the return type, and if it is a filter wrapper type, I take the filter out and apply it.
public class JsonFilterAwareMappingJackson2HttpMessageConverter extends
MappingJackson2HttpMessageConverter {
private boolean prefixJson = false;
@Override
public void setPrefixJson(boolean prefixJson) {
this.prefixJson = prefixJson;
super.setPrefixJson(prefixJson);
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
JavaType javaType = getJavaType(clazz);
try {
return this.getObjectMapper().readValue(inputMessage.getBody(), javaType);
}
catch (IOException ex) {
logger.error("Could not read JSON: " + ex.getMessage());
throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
}
}
@Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
ObjectMapper objectMapper = getObjectMapper();
JsonGenerator jsonGenerator =
objectMapper.getJsonFactory().createJsonGenerator(outputMessage.getBody(), encoding);
// A workaround for JsonGenerators not applying serialization features
// https://github.com/FasterXML/jackson-databind/issues/12
if (objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
jsonGenerator.useDefaultPrettyPrinter();
}
try {
if (this.prefixJson) {
jsonGenerator.writeRaw("{} && ");
}
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
if (object instanceof FilterAppliedJsonObject) {
FilterAppliedJsonObject viewObject = FilterAppliedJsonObject.class.cast(object);
objectMapper.setFilters(viewObject.getFilters());
objectMapper.writeValue(jsonGenerator, viewObject.getObject());
} else if (object == null) {
jsonGenerator.writeNull();
} else {
objectMapper.writeValue(jsonGenerator, object);
}
}
catch (JsonProcessingException ex) {
logger.error("Could not write JSON: " + ex.getMessage());
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
}
I use java @config instead of xml configuration as much as I can, so I do:
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
converters.add(new JsonFilterAwareMappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
I think this post will help you if you want to register this kind of conversion in xml