Recently I have faced a problem where I was asked to stop serializing selected object’s properties into JSON
(to protect sensible information from being logged in json style logs). Code was using Jackson library which has
lovely @JsonIgnore annotation specially designed for this type of problems. It almost looked too easy
but luckily it was bit more complicated and had a change to learn more about Jackson internals.
Issue was that the object was used as a rest api request so I couldn’t just ignore a field as it will invalidate
the request. At the same time it was being logged into the application log in the json format (json is easier to
feed to Logstash) and we didn’t wanted the field to be logged as it contains information not suitable for logging.
During a search for a solution I had stumble upon @JsonView which looked promising but unfortunately it wasn’t
working as it works as inclusion(you tell it which property you want) but I needed exclusion(you tell it which property
you don’t want).
At the I was forced to extend a few Jackson classes and configure a mapper to use them.
Firstly I had to to create a custom property writer which gave me full control over property serialization so I could
replace real property value with ‘*’.
The next step was to write a custom bean modifier in which I could configure custom property write on property by property
base. I have just used regexp to match potentially sensitive fields but you can always go a step further and create
an annotation.