spring-boot - 如何使用 Jackson 进行 Spring Controller 方法特定的序列化?
问题描述
我有两个不同的字符串字段序列化程序。我想根据调用 Controller 方法上的注释有条件地使用它们中的任何一个。我正在研究通过 Jackson 执行此操作的不同方法(例如 annotationIntrospector、JsonView 等)。但是,我看不到在序列化期间可以使用方法注释的任何地方。我可能可以检查我是否可以遵循类似于 Jackson 如何实现 JsonViews 但尚未找到解决方案的方法。
这是用例。
// Dto
public class MyDto {
@Masked //Mask the fields with an option to avoid masking based controller method annotation.
private final String stringField;
// getters, setters.
}
// controller.
// default behavior is to serialize masked.
@ResponseBody
public MyDto getMaskedDto() {
// return dto with masked value.
return this.someService.getDto();
}
// Controller
@IgnoreMasking // Do not mask the dto if method is annotated with @IgnoreMasking.
@ResponseBody
public MyDto getDtoSkipMasking() {
// return dto without masking String field value.
return this.someService.getDto();
}
解决方案
您可以扩展 JackonStdSerializer
并覆盖该serialize
方法。
所以是这样的:
- 创建一个新的
CustomSerializer
类扩展StdSerializer
- 覆盖
serialize
方法 - 在被覆盖的方法中,检查是否存在正在序列化的对象,以确定是否存在您的自定义注释(即
IgnoreMasking
)。你可以通过反射来做到这一点 - 做你的处理
- 将您的自定义序列化程序注册到 Jackson 的 ObjectMapper 配置中作为新的
SimpleModule
推荐阅读
- image - 无法从用 Flutter 编写的 Web 应用程序下载图像
- powershell - 试图通过 Powershell 打印一个目录
- xcode12 - 项目未在 Xcode 12.5 中运行
- javascript - React:如何将函数内部的数组传递给返回(JSX)
- google-play - 亚马逊相当于 Google Play 的“测试卡,总是拒绝”
- javascript - 平滑缩放画布
- vue.js - 在 web 哈希历史模式下使用 Vue 预渲染插件和 Vue Router
- android - OpenCV Android Studio 模块导入问题
- c++ - Clang ASTContext::mergeTypes 函数的用途?复合类型?
- redux - 如何从 redux 迁移到 redux 工具包