mst*_*fdz 91 java json jackson
我需要在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
}
}
}
Run Code Online (Sandbox Code Playgroud)
做这个的最好方式是什么?
Sha*_*her 168
JsonNode是不可变的,用于解析操作.但是,它可以被转换为ObjectNode(和ArrayNode)允许突变:
((ObjectNode)jsonNode).put("value", "NO");
Run Code Online (Sandbox Code Playgroud)
对于数组,您可以使用:
((ObjectNode)jsonNode).putArray("arrayName").add(object.ge??tValue());
Run Code Online (Sandbox Code Playgroud)
添加一个答案,因为其他一些人在已接受的答案的评论中表示赞同,他们在尝试转换为 ObjectNode(包括我自己)时遇到此异常:
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
Run Code Online (Sandbox Code Playgroud)
解决方案是获取“父”节点,并执行put,有效地替换整个节点,而不管原始节点类型如何。
如果您需要使用节点的现有值“修改”节点:
get 的值/数组 JsonNodeput给父母。代码,其中的目标是修改和subfield的子节点:NodeANode1
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");
Run Code Online (Sandbox Code Playgroud)
学分:
感谢wassgreen@,我从这里得到了这个灵感
小智 6
@Sharon-Ben-Asher 的回答没问题。
但就我而言,对于数组,我必须使用:
((ArrayNode) jsonNode).add("value");
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为您可以将其转换为 ObjectNode 并使用put方法。像这样
ObjectNode o = (ObjectNode) jsonNode;
o.put("value", "NO");
| 归档时间: |
|
| 查看次数: |
90662 次 |
| 最近记录: |