wajda wajda - 5 months ago 123x
Java Question

Jackson: How to add custom property to the JSON without modifying the POJO

I am developing REST interface to my app using Jackson to serialize my POJO domain objects to JSON representation. I want to customize the serialization for some types to add additional properties to the JSON representation that do not exist in POJOs (e.g. add some metadata, reference data, etc). I know how to write my own

, but in that case I would need to explicitly call
methods for each property of my object while all I need is just to add an additional property. In other words I would like to be able to write something like:

public void serialize(TaxonomyNode value, JsonGenerator jgen, SerializerProvider provider) {
jgen.writeAllFields(value); // <-- The method I'd like to have
jgen.writeObjectField("my_extra_field", "some data");

or (even better) to somehow intercept the serialization before the
call, e.g.:

@Override void beforeEndObject(....) {
jgen.writeObjectField("my_extra_field", "some data");

I thought I could extend
and override its
method but it's declared
and also I couldn't fine an easy way to create a new instance of
without providing it with all the type metadata details practically duplicating a good portion of Jackson. So I've given up on doing that.

My question is - how to customize Jackson's serialization to add additional stuff to the JSON output for particular POJOs without introducing too much of the boilerplate code and reusing as much as possible of the default Jackson behaviour.


After looking more on the Jackson source code I concluded that it's simply impossible to achieve without writing my own BeanSerializer, BeanSerializerBuilder and BeanSerializerFactory and provide some extension points like:

/* Extension points

protected void beforeEndObject(T bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JSONException {
    // May be overridden

protected void afterStartObject(T bean, JsonGenerator jgen, SerializerProvider provider) throws IOException, JSONException {
    // May be overridden

Unfortunately I had to copy and paste entire Jackson's BeanSerializer source code to MyCustomBeanSerializer because the former is not developed for extensions declaring all the fields and some important methods (like serialize(...)) as final