有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

基于Jersey和Jackson查询参数的java动态属性过滤

我想根据请求的查询参数过滤掉由Jackson生成的响应体的某些属性

泽西终点站

@Path("zoo/{id}")
@GET
public Response getZoos(@PathParam("id") String id, 
@QueryParam("animalsFilter") List<String> animals) {
    ....
    var zoos = Arrays.asList(zooDto1, zooDto2);
    return Response.ok().entity(zoos).build();
}

ZooDto看起来

public class ZooDto {
    private Zebra zebra;
    private Elephant elephant;
    ...
}

预期结果:

如果查询参数animals只包含zebra,我希望返回以下JSON:

[
    {
        "zebra": {
        ...
        }
    },
    ...
]

如果查询参数animals包含zebraelephant,我希望返回以下JSON:

[
    {
        "zebra": {
        ...
        },
        "elephant": {
        ...
        }
    },
    ...
]

迄今为止尝试过的方法:

  1. @JsonInclude(value =...不工作,因为我无法访问要筛选的animals列表
  2. @JsonFilter("...似乎可以工作,但我需要为每个过滤器生成相当多的代码
public static class BeanFilterImpl extends SimpleBeanPropertyFilter {
    @Override
    public void serializeAsField(
    ...
  1. filterProvider.addFilter("filter", SimpleBeanPropertyFilter.filterOutAllExcept(animals));看起来也很有希望,但我需要将这个过滤器添加到对象映射器中,我在接收animals的控制器类中没有这个过滤器。 我已将ObjectMapper注册为^{
@Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {

    private final ObjectMapper objectMapper;

    public JacksonConfig() {
        objectMapper = new ObjectMapper()
... 
  1. 使用SelectableEntityFilteringFeature听起来是正确的做法,但根据需要配置应用程序并没有改变任何事情(比如here)。我可能做错了什么,resourceConfig.isEnabled(SelectableEntityFilteringFeature.class)正在返回false
@ApplicationPath("")
public class MyAppConfig extends ResourceConfig {
    public MyAppConfig() {
        register(SelectableEntityFilteringFeature.class);
        property(SelectableEntityFilteringFeature.QUERY_PARAM_NAME, "select");
        register(JacksonFeature.class);
    }

而我的build.gradle包含

implementation group: 'org.glassfish.jersey.ext', name: 'jersey-entity-filtering', version: '2.34'

当我将select=elephant添加到查询参数时,将返回整个(未过滤的)实体。 此外,我不确定SelectableEntityFilteringFeature是否正在处理DTO列表

如何在不添加太多代码的情况下实现此过滤功能


共 (0) 个答案