我使用@JsonFilter有选择地过滤掉同一对象上的属性,当时 Spring 不(并且仍然不?)支持这个,所以我注册了一个自定义 MappingJackson2HttpMessageConverter 来检查返回类型,如果它是一个过滤器包装类型,我取出过滤器并应用它。
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);
}
}
}
我尽可能多地使用 java @config 而不是 xml 配置,所以我这样做:
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
converters.add(new JsonFilterAwareMappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
如果您想在 xml 中注册这种转换,我认为这篇文章会对您有所帮助