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:
objectis a configuration object- And
key-valueare configuration settings - In the above example one of the
keyispasswordand I need to mask/change the respectivevalueof 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:
Filter: filter and control serialization of properties
How to setup: The annotation
@JsonFilterapplies a named filter to a class (bean). That name can be looked up in a registry to find a customPropertyFilterimplementation (e.g. an extension of abstractSimpleBeanPropertyFilter). The registry is aFilterProviderwhich can be configured with yourObjectMapper.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. TheFilterProviderthen controls if and how the property is serialized.See:
Modifier: modify serialization at runtime, dynamically/conditional
For example
BeanSerializerModifieras solution to hide a field dynamically - based on a runtime value condition. See Skip objects conditionally when serializing with jackson.Static masking
(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.