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

后端 未结 11 1273
南方客
南方客 2020-11-27 03:10

I am developing a REST interface for my app using Jackson to serialize my POJO domain objects to JSON representation. I want to customize the serialization for some types to

11条回答
  •  感情败类
    2020-11-27 03:53

    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.

提交回复
热议问题