Customize Jackson ObjectMapper to Read custom Annotation and mask fields annotated

1,050 views
Skip to first unread message

Saurabh Bhardwaj

unread,
Jan 23, 2016, 12:11:06 PM1/23/16
to jackson-user
I have a requirement where I have created a Custom Annotation @MaskSensitiveData. I annotate sensitive fields. like
class MyBean {
    String userName;
    @MaskSensitiveData
    String cardNumber;
    String abc;
    String xyz;
}

ObjectMapper mapper = new ObjectMapper();
    String json = null;
    AnnotationIntrospector primary = new JaxbAnnotationIntrospector();
    AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
    mapper.setAnnotationIntrospector(pair);
    try {
        json = mapper.writeValueAsString(obj);
        /*
         * if(json != null ) { json = getLoggableString(json); }
         */
    } catch (Exception e) {
        return "Unable to convert to Json object:" + obj.toString() + " Message: " + e.getMessage();

    }
I am using Jackson ObjectMapper to convert objct to Json like. I need to customize Object Mapper to mask cardNumber field in return json. Please suggest

Tatu Saloranta

unread,
Jan 23, 2016, 6:55:41 PM1/23/16
to jackso...@googlegroups.com
By masking, do you mean that output String should be some other static String (like "xxxxxx")?

One possibility would be a simple custom serializer. Slightly simpler could be using `@JsonSerializer(converter=MaskingConverter.class)` where MaskingConverter would implement Converter<String,String>.

And to make your custom annotation indicate use of this, you would define it as:

  @Retention(RetentionPolicy.RUNTIME)
  @JacksonAnnotationsInside
  @JsonSerializer(converter=MaskingConverter.class)`
  public @interface @MaskSensitiveData { }

which would just mean that all annotations included should be added to ones for annotated entity (method)

-+ Tatu +-


--
You received this message because you are subscribed to the Google Groups "jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user...@googlegroups.com.
To post to this group, send email to jackso...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages