您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为杰克逊添加动态JSON属性作为Java Pojo

为杰克逊添加动态JSON属性作为Java Pojo

您可以使用JsonAnyGetter批注来创建动态key- value对。下面的示例显示了如何为同一Label生成3个不同的键:

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<Label> labels;

    public AddLabel(String labelName) {
        this.labels = new ArrayList<>();
        this.labels.add(Label.add(labelName));
    }

    public List<Label> getLabels() {
        return labels;
    }

    public static class Label {

        private final String key;
        private final String value;

        private Label(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public static Label add(String value) {
            return new Label("add", value);
        }

        public static Label remove(String value) {
            return new Label("remove", value);
        }

        public static Label set(String value) {
            return new Label("set", value);
        }

        @JsonAnyGetter
        public Map<String, String> getDynamic() {
            return Collections.singletonMap(key, value);
        }
    }
}

上面的代码打印:

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

也可以看看:

java 2022/1/1 18:31:02 有640人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶