ab m
ab m

Reputation: 422

How to do Spring Controller method specific serialization with Jackson?

I have two different serializers for String fields. I want to use either of them conditionally based on an annotation present on the calling Controller method. I'm looking at different ways of doing this via Jackson (eg. annotationIntrospector, JsonView etc). However, I do not see anywhere I can use method annotation during serialization. I can probably check if I can follow something similar to how Jackson implements JsonViews but haven't got to a solution yet.

Here is the use case.

// 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();
}

Upvotes: 0

Views: 1082

Answers (1)

allkenang
allkenang

Reputation: 1645

You could extend Jackon's StdSerializer and override the serialize method.

So something like this:

  1. Create a new CustomSerializer class extending StdSerializer
  2. Override the serialize method
  3. In the overridden method, check for the existence of the object being serialised for the existence of your custom annotation (ie IgnoreMasking). You can do this via reflection
  4. Do your processing
  5. Register your custom serializer into Jackson's ObjectMapper configuration as a new SimpleModule

Upvotes: 1

Related Questions