Reputation: 422
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
Reputation: 1645
You could extend Jackon's StdSerializer
and override the serialize
method.
So something like this:
CustomSerializer
class extending StdSerializer
serialize
methodIgnoreMasking
). You can do this via reflectionSimpleModule
Upvotes: 1