为 jackson 添加动态 json 属性作为 java pojo [英] Adding a dynamic json property as java pojo for jackson
问题描述
我需要从 Java pojo 创建一个像这样的 Json 负载:
I need to create a Json payload like this from Java pojo :
{ "update" : {
"labels" : [{"add" : "A label"} ]
}
}
所以我创建了一个这样的 Java pojo:
so I created a Java pojo like this :
@JsonRootName(value = "update")
public class AddLabel{
@JsonProperty("labels")
public List<Label> labels;
public AddLabel(String labelName){
this.labels = new ArrayList<>();
this.labels.add(new Label(labelName);
}
public static class Label{
public String add;
public Label(String labelName){
this.add = labelName;
}
}
}
我喜欢将 Label 类中的add"属性设为动态,这样它也可以采用诸如remove"、set"之类的值.除了为每个人创建另一个 POJO 之外,还有其他方法可以做到这一点吗?
I like to have the "add" property in Label class as dynamic, so that it can also take values such as "remove", "set" . Is there a way to do this other than creating another POJO's for each of them?
推荐答案
您可以使用 JsonAnyGetter 注释,允许创建动态 key-value
对.下面的例子展示了我们如何为同一个 Label
类生成 3 个不同的键:
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<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"
} ]
}
另见:
这篇关于为 jackson 添加动态 json 属性作为 java pojo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!