Dynamic change of JsonProperty name using Jackson java library

后端 未结 1 1344
青春惊慌失措
青春惊慌失措 2021-01-27 22:05

I use Jackson 2.9.8 for converting my below POJO as JSON:

public class ResponseEntity implements Serializable {

    priva         


        
1条回答
  •  执笔经年
    2021-01-27 23:07

    You can provide name in constructor and use JsonAnyGetter. Below solution:

    import com.fasterxml.jackson.annotation.JsonAnyGetter;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    import java.io.Serializable;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    
    public class JsonApp {
    
        public static void main(String[] args) throws Exception {
            ResponseEntity entity = new ResponseEntity("dynList",
                    Collections.singletonList(Collections.singletonMap("key", "value1")));
    
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
    
            System.out.println(mapper.writeValueAsString(entity));
        }
    }
    
    class ResponseEntity implements Serializable {
    
        private static final long serialVersionUID = 1L;
        private int total_record_count;
        private int filtered_record_count;
    
        private String propertyName;
    
        @JsonIgnore
        private List> entityList;
    
        public ResponseEntity(String propertyName, List> entityList) {
            this.propertyName = propertyName;
            this.entityList = entityList;
            this.filtered_record_count = entityList.size();
        }
    
        @JsonAnyGetter
        public Map otherProperties() {
            return Collections.singletonMap(propertyName, entityList);
        }
    
        // other methods
    }
    

    prints:

    {
      "total_record_count" : 0,
      "filtered_record_count" : 1,
      "dynList" : [ {
        "key" : "value1"
      } ]
    }
    

    0 讨论(0)
提交回复
热议问题