Search code examples
javaserializationjacksonimmutables-library

Jackson Subclass serialization


I'm using an java API that I do not own and cannot modify. That API defines a class Aggregation which is a Immutables (immutables.github.io) abstract class with Jackson serialization and deserialization.

The class looks like

@Value.Immutable
@JsonSerialize(as = Immutable_Aggregation.class)
@JsonDeserialize(as = Immutable_Aggregation.class)
public abstract class Aggregation {

I want to add a field to Aggregation which should be picked up at serialization time, but instances of which can still be passed to methods accepting Aggregation.

I want to do something like:

public abstract class ExtendedAggregation extends Aggregation {}

Is this possible?


Solution

  • I haven't managed to inherit between two classes marked with @Value.Immutable as you would like, so I tried to use Jackson to solve the issue instead.

    Found the following approach, which uses the @JsonAppend annotation and mixins to add properties without touching the Aggregation class.

    First, define a mix-in class with the annotation:

    @JsonAppend(
        attrs = {
            @JsonAppend.Attr(value = "version")
    })
    public class AggregationMixin {}
    

    Register the Mixin with your ObjectMapper instance:

    mapper.addMixIn(Aggregation.class, AggregationMixin.class);
    

    Serialize the class by creating a dedicated ObjectWriter, in which you specify the value of the added property:

    ObjectWriter writer = om.writerFor(Aggregation.class).withAttribute("version", "42");
    ...    
    String output = writer.writeValueAsString(aggregationInstance);
    

    The @JsonAppend annotation can be configured to obtain its value in a multitude of ways. Consult its documentation for details.

    Some further reading :

    http://www.baeldung.com/jackson-advanced-annotations#jsonappend http://wiki.fasterxml.com/JacksonMixInAnnotations