Jackson dynamic property names

前端 未结 4 692
感动是毒
感动是毒 2020-11-27 16:46

I would like serialize an object such that one of the fields will be named differently based on the type of the field. For example:

public class Response {
          


        
4条回答
  •  心在旅途
    2020-11-27 17:23

    I had a simpler solution using @JsonAnyGetter annotation, and it worked like a charm.

    import java.util.Collections;
    import java.util.Map;
    
    public class Response {
        private Status status;
        private String error;
    
        @JsonIgnore
        private Object data;
    
        [getters, setters]
    
        @JsonAnyGetter
        public Map any() {
            //add the custom name here
            //use full HashMap if you need more than one property
            return Collections.singletonMap(data.getClass().getName(), data);
        }
    }
    

    No wrapper needed, no custom serializer needed.

提交回复
热议问题