java - 以编程方式忽略(省略)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...
解决方案
这个问题听起来像是一个完美的装饰器设计模式使用。使用获取原始 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)
推荐阅读
- node.js - 反应:不知道如何使用复选框选择表行并使用 node.js 将值发送到服务器端
- java - 'java.lang.NumberFormatException: Invalid double' 用于欧洲语言,使用 Kotlin
- android - 如何避免 Android TalkBack 读取 SwitchCompat TextOn/TextOff
- html - 如何找出动态链接可以采用哪些参数?
- python - 具有复数的 Python interp2D
- matlab - 如何在matlab中使用if来处理2个矩阵条件?
- algorithm - 具有多个源顶点的边加权 DAG 中的最短路径?
- python - 在python中解析.ini文件
- c - 如何在 C 或 CPP 中计算虚拟机上的虚拟内核数
- java - 如何根据属性文件或环境变量选择 Logback appender