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

您可以使用JsonAnyGetter批注,该批注允许创建动态键值对.下面的示例显示了如何为同一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 labels;

public AddLabel(String labelName) {

this.labels = new ArrayList<>();

this.labels.add(Label.add(labelName));

}

public List 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 getDynamic() {

return Collections.singletonMap(key, value);

}

}

}

上面的代码打印:

{

"labels" : [ {

"add" : "A label"

}, {

"remove" : "Remove"

}, {

"set" : "Set"

} ]

}

也可以看看:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值