【发布时间】:2025-12-06 09:25:01
【问题描述】:
Jackson 2.0 允许使用 @JsonView 过滤 JAX-RS 资源。
以下示例显示了一种在资源响应中忽略人们年龄的方法。
不幸的是,每个 JAX-RS 方法都必须使用 @JsonView 进行注释。
public class View {
public static class Public {}
public static class Private {}
}
public class People {
@JsonView(View.Public) String name;
@JsonView(View.Private) int age;
}
@Path("/people")
public class PeopleResource {
@GET
@JsonView(View.Public)
public List<People> get() {
return peoples.get();
}
@GET
@Path("/id")
@JsonView(View.Public)
public People get(@PathParam("id") int id) {
return people.get(id);
}
}
我发现全局过滤应用程序资源的唯一方法是使用 MixIn。
public class PeopleMixIn {
@JsonIgnore int age;
}
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper = new ObjectMapper();
public ObjectMapperProvider() {
mapper.addMixInAnnotations(People.class, PeopleMixIn.class);
}
public ObjectMapper getContext(Class<?> type) { return mapper; }
}
有没有办法用 JsonView 配置 Jackson 的 ObjectMapper?或者对资源/应用程序的每个方法都应用过滤器?
【问题讨论】:
-
您的目的只是为了隐藏响应中的某些属性吗?
标签: java jersey jax-rs jackson