我只需要在一个控制器中过滤一些属性。
Fasterxml JsonFilter在控制器中与ObjectMapper一起使用时工作,如下所示
FilterProvider filter2 = new SimpleFilterProvider().addFilter("somefilter",
SimpleBeanPropertyFilter.filterOutAllExcept("prop1","prop2"));
具有类似的对象
@JsonFilter("somefilter")
public class Bar{
String prop1;
String prop2;
String prop3;
}
但当试图用弹簧控制器返回同一物体时
@RequestMapping(value = "/path", method = RequestMethod.GET)
protected @ResponseBody Foo handleGet( ..
其中
public class Foo{
Bar p1;
Bar p2;
}
Bar属性被完全省略。在这种情况下,我们需要返回未过滤的对象。
我必须使用控制器中的对象映射器来返回整个对象。
有没有办法禁用控制器的过滤器?
您可以尝试MappingJacksonValue
来设置Jackson过滤器提供程序,以便在Spring控制器中使用序列化POJO。
来自AbstractJackson2HttpMessageConverter:的源代码
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
...
try {
...
if (object instanceof MappingJacksonValue) {
MappingJacksonValue container = (MappingJacksonValue) object;
...
filters = container.getFilters();
}
...
ObjectWriter objectWriter;
if (serializationView != null) {
objectWriter = this.objectMapper.writerWithView(serializationView);
}
else if (filters != null) {
objectWriter = this.objectMapper.writer(filters);
}
else {
objectWriter = this.objectMapper.writer();
}
...
objectWriter.writeValue(generator, value);
...
}
应该可以通过在MappingJacksonValue
中设置的滤波器来重置objectMapper
中的FilterProvider
。在您的情况下,您可以尝试以下操作:
@RequestMapping(value = "/foo", method = RequestMethod.GET)
protected @ResponseBody MappingJacksonValue handleGet(...) {
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(foo);
FilterProvider filter = new SimpleFilterProvider().addFilter("somefilter", SimpleBeanPropertyFilter.serializeAllExcept());
mappingJacksonValue.setFilters(filter);
return mappingJacksonValue;
}
如果您只有一个控制器需要从Bar
中筛选出属性,您也可以考虑为特定控制器添加筛选器,而不是将其设置到ObjectMapper:中
@RequestMapping(value = "/bar", method = RequestMethod.GET)
protected @ResponseBody MappingJacksonValue handleGet(...) {
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(bar);
FilterProvider filter = new SimpleFilterProvider().addFilter("somefilter", SimpleBeanPropertyFilter.filterOutAllExcept("prop1","prop2"));
mappingJacksonValue.setFilters(filter);
return mappingJacksonValue;
}