So, the title basically describes what I need. Say, the bean to be serialized looks like this:
public class SomeBean {
public String someString;
}
I would like Jackson to serialize an instance of SomeBean like this:
{
someString: '<the value>',
__hash_someString: '<a proprietary hash of <the value>>'
}
This functionality should be generic. I don't want to write a specific serializer for SomeBean because this needs to happen at multiple locations. It is not an option to add the '__hash_someString' to the class itself because it would pollute the model.
Implementation
I would like Jackson to process the bean normally. But when it encounters a specific annotation (@GenerateHash) it should add another field to the object like before. So it would like this:
public class SomeBean {
@GenerateHash
public String someString;
}
The road so far
There are a lot of similar topics but none of them attempt something like this. I'm not really into the inner workings of Jackson Serialization but it seems you only get the option of modifying an object as a whole. I haven't found a way to intercept the serialization process of a field, only the value of that field.
I've tried to implement this using a BeanSerializerModifier and also tried some things with @Serializer. However, I usually end up in a infinite loop.
Resources I consulted are (not limited to):
- Jackson: How to add custom property to the JSON without modifying the POJO
- Jackson - custom serializer that overrides only specific fields
- Jackson JSON custom serialization for certain fields
- How do I call the default deserializer from a custom deserializer in Jackson
- http://techtraits.com/programming/2011/11/21/using-custom-serializers-with-jackson/
In short How can I get Jackson to serialize
public class SomeBean {
@GenerateHash
public String someString;
public String unaffectedString;
}
to this:
{
someString: '<the value>',
__hash_someString: '<a proprietary hash of <the value>>',
unaffectedString: '<some value>'
}