首页 > 解决方案 > 以编程方式忽略(省略)REST 服务的 JSON 响应中的特定字段,而不更改 DTO 对象类

问题描述

我有一个 DTO 类和一些 REST 服务,它们有时会返回(除其他外)这些 DTO 的列表。

我无法更改该 DTO,因为它已在项目的多个地方使用。

但是,仅对于一个特定的 REST 服务,我需要排除该 DTO 对象的一些字段。

基本上我需要能够仅在某个特定点应用此解决方案。

我尝试应用@JsonFilter("restrictionFilter")到我的 DTO 类,但是如果我每次将对象编组为 JSON 时不使用带有映射器的过滤器,则会出现错误,如下所示:

final String writeValueAsString = mapper.writer(
  new SimpleFilterProvider()
    .addFilter("restrictionFilter", 
                SimpleBeanPropertyFilter.filterOutAllExcept("name", "sizeInByte"))
  ).writeValueAsString(objectsList);

错误是无法解析 ID 为“restrictionFilter”的 PropertyFilter;没有配置 FilterProvider...

标签: javajsonrest

解决方案


这个问题听起来像是一个完美的装饰器设计模式使用。使用获取原始 DTO 的构造函数创建一个新的 DTO,并创建您想要的 get 方法或忽略您喜欢的任何 get 方法。例如:

public class NewDto {

    OldDto oldDto;

    public NewDto(OldDto oldDto){
        this.oldDto = oldDto;
    }

    public String getName(){
        return oldDto.getName();
    }
}

现在您只需要返回 NewDto 对象,如下所示:

return new NewDto(oldDto)

推荐阅读