使用Jackson过滤属性非常简单:
final FilterProvider filters = new SimpleFilterProvider().
addFilter(... the name of the filter ...,
SimpleBeanPropertyFilter.filterOutAllExcept(... enumeration of properties ...));
<object mapper>.writer(filters).writeValueAsString(... the bean ...);
Run Code Online (Sandbox Code Playgroud)
我想在我的Jersey REST应用程序中集成它.API用户可以通过提供查询字符串来过滤属性:
https://the-api/persons?fields=name,age,location,gender
Run Code Online (Sandbox Code Playgroud)
泽西岛最优雅的方式是什么?我可以轻松地在我的资源方法中执行上述操作,但这会以某种方式杀死Jersey的优雅.此外,我相信为每个请求创建一个新的ObjectMapper会有性能损失.
我可以编写一个从上下文中MessageBodyWriter获取fields查询参数,UriInfo并在应用基于fields查询参数的过滤器时将实体序列化为json .这是最好的方法吗?像这样:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JustTesting implements MessageBodyWriter<Object> {
@Context
UriInfo uriInfo;
@Context
JacksonJsonProvider jsonProvider;
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.equals(mediaType);
}
public long getSize(Object object, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return …Run Code Online (Sandbox Code Playgroud)