How to use dynamic property names for a Json object

前端 未结 3 1112
悲&欢浪女
悲&欢浪女 2020-12-02 02:38

How can we make the JSON property name dynamic. For example

public class Value {
    @JsonProperty(value = \"value\")
    private String val;

    public vo         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 03:04

    You could have all the possible names as variables, and annotate them so they are ignored if null. This way you only get in your JSON the one that has a value

    Then change your setter to feed into the variable mapped to the key you want.

    class Value {
    
        @JsonProperty("val")
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String val;
    
        @JsonProperty("new_key")
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String newKey;
    
        @JsonProperty("any_random_string")
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String anyRandomString;
    
        public void setVal(String s) {
            if(/* condition1 */)
                this.val = s;
            else if (/* condition2 */) {
                this.newKey = s;
            } else  if (/* condition3 */) {
                this.anyRandomString = s;
            }
        }
    
    }
    

提交回复
热议问题