2.7.8. JSON Provider
2.7.8.1. RESTEasy Jackson2 中的 JsonFilter 支持
JsonFilter
允许您为类添加 @JsonFilter
注释,从而促进动态过滤。以下示例定义了从 nameFilter
类映射到过滤器实例,然后在对实例序列化到 JSON 格式时过滤 bean 属性。
@JsonFilter(value="nameFilter") public class Jackson2Product { protected String name; protected int id; public Jackson2Product() { } public Jackson2Product(final int id, final String name) { this.id = id; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
@JsonFilter
注释资源组,以过滤出不应在 JSON 响应中序列化的属性。若要映射过滤器 ID 和实例,您必须创建另一个 Jackson 类,并将 ID 和过滤实例映射到此类,如下例中所示。
public class ObjectFilterModifier extends ObjectWriterModifier { public ObjectFilterModifier() { } @Override public ObjectWriter modify(EndpointConfigBase<?> endpoint, MultivaluedMap<String, Object> httpHeaders, Object valueToWrite, ObjectWriter w, JsonGenerator jg) throws IOException { FilterProvider filterProvider = new SimpleFilterProvider().addFilter( "nameFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); return w.with(filterProvider); } }
在上面的示例中,方法 mod ()
负责过滤除 name
属性外的所有属性,然后再写入响应。要实现此目的,RESTEasy 必须了解此映射信息。您可以在 WriterInterceptor
或 servlet 过滤器中设置映射信息,如下例所示。
示例:使用 WriterInterceptor 设置 ObjectFilterModifier
@Provider public class JsonFilterWriteInterceptor implements WriterInterceptor{ private ObjectFilterModifier modifier = new ObjectFilterModifier(); @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { //set a threadlocal modifier ObjectWriterInjector.set(modifier); context.proceed(); } }
示例:使用 Servlet Filter 设置 ObjectFilterModifier
public class ObjectWriterModifierFilter implements Filter { private static ObjectFilterModifier modifier = new ObjectFilterModifier(); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ObjectWriterInjector.set(modifier); chain.doFilter(request, response); } @Override public void destroy() { } }
现在,RESTEasy 可以从 ThreadLocal
变量获取 ObjectFilterModifier
,并在写入响应前将其配置为修改 ObjectWriter
。