Jackson Generics with variable JsonProperty (usage with generics)

后端 未结 2 1202
青春惊慌失措
青春惊慌失措 2020-12-18 14:48

I have class that looks like this:

public class Data {

    @JsonProperty(\"difficulties\")
    private U[] data;

    // ... geter setter construct         


        
2条回答
  •  忘掉有多难
    2020-12-18 15:13

    You can use @JsonAnyGetter annotation.

    public class Data {
    
        @JsonIgnore
        private U[] data;
    
        @JsonIgnore
        private String propertyName;
    
        public Data(String propertyName) {
            this.propertyName = propertyName;
        }
    
        // ... geter setter
    
        @JsonAnyGetter
        public Map any() {
            return Collections.singletonMap(propertyName, data);
        }
    }
    

    And use it like below:

    Data difficulties = new Data<>("difficulties");
    

    write whatever you want instead of "difficulties" string. Set your list to Data generic class instead of Difficulties object if you want

提交回复
热议问题