Jackson custom serializer by field name?

前端 未结 2 1968
傲寒
傲寒 2021-01-20 21:03

I have a POJO to be serialized which has field of type Object named representation and I have a custom serializer written for it.

2条回答
  •  天命终不由人
    2021-01-20 21:43

    Have you ever considered Jackson mix-in annotations?

    Jackson mix-in annotations

    It's a great alternative when modifying the classes is not an option. You can think of it as kind of aspect-oriented way of adding more annotations during runtime, to augment statically defined ones.

    Define a mix-in annotation interface (class would do as well):

    public interface EventMixIn {
    
        @JsonProperty("representation")
        @JsonSerialize(using = CustomSerializer.class)
        Object getRepresentation();
    }
    

    Then configure ObjectMapper to use the defined interface as a mix-in for your POJO:

    ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
                                            .addMixIn(User.Event.class, EventMixIn.class); 
    

    Usage considerations

    Here are some usage considerations:

    • All annotation sets that Jackson recognizes can be mixed in.
    • All kinds of annotations (member method, static method, field, constructor annotations) can be mixed in.
    • Only method (and field) name and signature are used for matching annotations: access definitions (private, protected, ...) and method implementations are ignored.

    For more details, you can have a look at this page.

提交回复
热议问题