首页 > 解决方案 > 如何使用 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();
}

标签: spring-bootspring-mvcjacksonjackson-databind

解决方案


您可以扩展 JackonStdSerializer并覆盖该serialize方法。

所以是这样的:

  1. 创建一个新的CustomSerializer类扩展StdSerializer
  2. 覆盖serialize方法
  3. 在被覆盖的方法中,检查是否存在正在序列化的对象,以确定是否存在您的自定义注释(即IgnoreMasking)。你可以通过反射来做到这一点
  4. 做你的处理
  5. 将您的自定义序列化程序注册到 Jackson 的 ObjectMapper 配置中作为新的SimpleModule

推荐阅读