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

Jackson 2.5 introduced the @JsonAppend annotation, which can be used to add “virtual” properties during serialization. It can be used with the mixin functionality to avoid modifying the original POJO.

The following example adds an ApprovalState property during serialization:

@JsonAppend(
    attrs = {
        @JsonAppend.Attr(value = "ApprovalState")
    }
)
public static class ApprovalMixin {}

Register the mixin with the ObjectMapper:

mapper.addMixIn(POJO.class, ApprovalMixin.class);

Use an ObjectWriter to set the attribute during serialization:

ObjectWriter writer = mapper.writerFor(POJO.class)
                          .withAttribute("ApprovalState", "Pending");

Using the writer for serialization will add the ApprovalState field to the ouput.

Leave a Comment