I'm looking for a solution to serialize a POJO object property based on some other property value within the same POJO using Jackson.
If a property value matches some criteria then other property values should be changed as per requirement.
For example, below is my JSON object:
{
"testProperty": "testValue",
"object": [{
"key": "password",
"value": "passwordValue"
},
{
"key": "key2",
"value": "value2"
}]
}
In above case, if key
's value matches some criteria then I should be able to change the value of value
.
Why this is required:
object
is a configuration objectkey
-value
are configuration settingskey
is password
and I need to mask/change the respective value
of that.One more point to add, here in this example the properties are key
and value
, but if we find some solution to get it applied generically to any other properties dynamically then that would be great.
Annotating the properties can be one way but haven't found any way within Jackson to do so with custom serializers.
Thanks in advance.
Any help will be appreciated.
Jackson has following concepts for that:
How to setup:
The annotation @JsonFilter
applies a named filter to a class (bean).
That name can be looked up in a registry to find a custom PropertyFilter
implementation (e.g. an extension of abstract SimpleBeanPropertyFilter
).
The registry is a FilterProvider
which can be configured with your ObjectMapper
.
How it works:
So when the ObjectMapper instance is about to serialize your bean it will recognize the filter and use the logic to a FilterProvider
. The FilterProvider
then controls if and how the property is serialized.
See:
For example BeanSerializerModifier
as solution to hide a field dynamically - based on a runtime value condition. See Skip objects conditionally when serializing with jackson.
(Probably not for your variable key/value pairs, but generally good approach for fields designed to hide sensitive data)
See Mask json fields using jackson which tries to add a specific serializer which derives its mask from a custom annotation.