Adding a dynamic json property as java pojo for jackson

后端 未结 2 1363
滥情空心
滥情空心 2020-12-07 04:13

I need to create a Json payload like this from Java pojo :

{ \"update\" : {
    \"labels\" : [{\"add\" : \"A label\"} ]
    }
 }

so I crea

2条回答
  •  猫巷女王i
    2020-12-07 04:55

    You can use JsonAnyGetter annotation which allows to create dynamic key-value pairs. Below example shows how we can generate 3 different keys for the same Label class:

    import com.fasterxml.jackson.annotation.JsonAnyGetter;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonRootName;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.SerializationFeature;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    
    public class JsonApp {
    
        public static void main(String[] args) throws Exception {
            AddLabel label = new AddLabel("A label");
            label.getLabels().add(AddLabel.Label.remove("Remove"));
            label.getLabels().add(AddLabel.Label.set("Set"));
    
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
    
            System.out.println(mapper.writeValueAsString(label));
        }
    }
    
    @JsonRootName(value = "update")
    class AddLabel {
    
        @JsonProperty("labels")
        private List

    Above code prints:

    {
      "labels" : [ {
        "add" : "A label"
      }, {
        "remove" : "Remove"
      }, {
        "set" : "Set"
      } ]
    }
    

    See also:

    • Jackson @JsonAnyGetter and @JsonAnySetter Example
    • Jackson Annotation Examples
    • How to use dynamic property names for a Json object

提交回复
热议问题