我需要在Java中更改一个JSON属性值,我可以正确地得到这个值,但我无法修改JSON。
下面是代码
JsonNode blablas = mapper.readTree(parser).get("blablas");
for (JsonNode jsonNode : blablas) {
String elementId = jsonNode.get("element").asText();
String value = jsonNode.get("value").asText();
if (StringUtils.equalsIgnoreCase(elementId, "blabla")) {
if(value != null && value.equals("YES")){
// I need to change the node to NO then save it into the JSON
}
}
}做这件事最好的方法是什么?
发布于 2015-06-23 08:32:10
JsonNode是不可变的,用于解析操作。但是,可以将其转换为允许突变的ObjectNode (和ArrayNode):
((ObjectNode)jsonNode).put("value", "NO");对于数组,可以使用:
((ObjectNode)jsonNode).putArray("arrayName").add(object.getValue());发布于 2019-04-03 06:17:41
添加一个答案,一些人在接受的答案的评论中投了反对票,当他们试图转换到ObjectNode (包括我自己)时,他们得到了这个异常:
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode解决方案是获取“父”节点,并执行一个put**,,有效地替换整个节点,而不管原始节点类型如何。**
如果需要使用节点的现有值“修改”节点:
get JsonNode的值/数组put。代码,目标是修改subfield,后者是NodeA和Node1的子节点。
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");演职人员:
我从here得到了这个灵感,多亏了wassgreen@
发布于 2015-06-23 08:33:27
我认为您可以直接转换为ObjectNode并使用put方法。像这样
ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");
https://stackoverflow.com/questions/30997362
复制相似问题