Adding a dynamic json property as java pojo for jackson

后端 未结 2 1358
滥情空心
滥情空心 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条回答
  •  再見小時候
    2020-12-07 04:55

    Your specification isn't clear, you would have many of the same action (add, remove, etc) or just one at most?

    First Option
    In case you have at most single instance of the same action, you can replace the array with regular object:

    { "update" : {
        "labels" : {
           "add" : "A label",
           "remove" : "B label"
          }
        }
     }
    

    and then change your labels to a Map instead of List

    Second Option
    In case you have many instances of the same action, you can change the design of label to contain two fields, value and action

    { "update" : {
        "labels" : [{"action": "add", "value" : "A label"} ]
        }
     }
    

    And update Label accordingly:

      public static class Label{
        public String action;
        public String value 
        public Label(String action, String value){
           this.action = action;
           this.value = value; 
        }
      }
    

    You can also change action to enum which define all your possible actions

    Third Option
    If you really need to stick to your json design, you don't have a lot of options to define static typing class for a dynamic json. maybe it's possible to hack this somehow using jackons's polymorphism. But you can always just use the json objects and leave the labels as List

提交回复
热议问题