【发布时间】:2015-09-17 23:28:05
【问题描述】:
这里是json
{
"UserInfoService": {
"state": "active",
"message": [
"hello",
"world"
]
},
"UserProfileService": {
"state": "inactive",
"message": "[foo,bar]"
}
}
我有基于版本存储这些 jsonNode 的地图
例如:{"v1": jsonNode@1343, "v2":jsonNOde@1353543}
这是我的方法:
public class ModifyMap {
private Map<String,JsonNode> map = new HashMap<>();
private void updateNode(Foobar foo,String version, List<String> messages, String mainKey){
JsonNode rootNode = featureStatusNodes.get(version);
if (featureNode==null){
rootNode=mapper.createObjectNode();
}
JsonNode stateNode = mapper.convertValue(new Status(foo.getState()), JsonNode.class);
JsonNode messageNode = mapper.convertValue(messages, JsonNode.class);
((ObjectNode) rootNode).set("state",stateNode);
((ObjectNode) rootNode).set("message",messageNode);
rootNode.put(version, featureNode);
}
}
public class Status {
String state;
//getters and setters
}
public class FooBar {
Status status;
//getters and setters
}
这就是我所拥有的。
但是我将如何将传入参数的mainKey 设置为顶级节点。在上面的示例中,mainKey 将是 userInfoService。
要考虑的因素是
如果存在mainKeynode,则使用传递的值更新它
如果不存在,则创建一个并更新它。
请注意,示例中有两个mainKeys:userInfoService、userProfileService。
有一个top-level map 维护versions 到jsonNode 的映射。
在上述情况下,如果对于给定版本,如果 jsonNode 为 null,则创建一个并更新它。
如果对于给定版本,jsonNode(例如userInfoService)存在但userProfileService 不存在,则更新根以包含userProfileService。
如果仅对已经存在的userInfoService 需要更新,则进行相应更新。
【问题讨论】:
标签: java json jackson fasterxml