对来自RESTful Web服务的响应中的字段进行动态过滤,要求返回域对象列表

问题描述 投票:0回答:1

考虑到使用Spring Boot框架开发的RESTful Web服务,我想要一种抑制响应中所有用户的birthDate的方法。这是我在寻找解决方案后实现的方法:

@RestController
public class UserResource {

    @Autowired
    private UserDAOservice userDAOService;

    @GetMapping("/users")
    public MappingJacksonValue users() {
        List<User> users = userDAOService.findAll();

        SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter
                .filterOutAllExcept("id", "name");

        FilterProvider filters = new SimpleFilterProvider().addFilter(
                "UserBirthDateFilter", filter);

        MappingJacksonValue mapping = new MappingJacksonValue(users);

        mapping.setFilters(filters);

        return mapping;
    }
}

但是,当我在浏览器中单击其余端点时,仍然可以在响应中看到用户的出生日期:

{
    "id": 1,
    "name": "Adam",
    "birthDate": "1980-03-31T16:56:28.926+0000"
}

问题1:我可以使用什么API来实现我的目标?

接下来,假设我想结合过滤坚持使用HATEOAS,我该怎么做。我无法弄清楚可以一起使用这两个功能的API:

@GetMapping("/users/{id}")
public EntityModel<User> users(@PathVariable Integer id) {
    User user = userDAOService.findById(id);
    if (user == null) {
        throw new ResourceNotFoundException("id-" + id);
    }

    EntityModel<User> model = new EntityModel<>(user);
    WebMvcLinkBuilder linkTo = linkTo(methodOn(this.getClass()).users());
    model.add(linkTo.withRel("all-users"));

    //how do I combine EntityModel with filtering?
    return model;
}

问题2:如何将EntityModelMappingJacksonValue合并?

注意:我知道@JsonIgnore注释,但是它将对使用该域的所有端点应用过滤器;但是,我只想将过滤限制为上述两个端点。

java spring-boot jackson spring-rest hateoas
1个回答
0
投票

有一个更简单的方法,在您的传输对象(要发送回客户端的类)上,您可以简单地使用@JsonIgnore批注以确保该字段未序列化,并因此发送给客户端。因此,只需在您的生日类的User类中添加@JsonIgnore。

您还可以在此处阅读有关此方法的更多信息:

https://www.baeldung.com/jackson-ignore-properties-on-serialization

如果需要为不同的终结点返回不同的对象(对于您的情况,没有生日的用户,仅针对特定用户),您应该创建单独的传输对象,并将其用于各自的终结点。您可以将构造函数中的原始实体(用户)传递给这些类,然后复制所需的所有字段。

© www.soinside.com 2019 - 2024. All rights reserved.