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 object- And
key
-value
are configuration settings - In the above example one of the
key
ispassword
and I need to mask/change the respectivevalue
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.
CodePudding user response:
Jackson has following concepts for that:
Filter: filter and control serialization of properties
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:
- tutorial on Baeldung (2019): Serialize Only Fields that meet a Custom Criteria with Jackson
- article on CowTownCoder (2011): Advanced filtering with Jackson, Json Filters
Modifier: modify serialization at runtime, dynamically/conditional
For example BeanSerializerModifier
as 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.