如何在Java中修改JsonNode? [英] How to modify JsonNode in Java?
本文介绍了如何在Java中修改JsonNode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在Java中更改JSON属性的值,我可以正确获取值但是我无法修改JSON。
I need to change a JSON attribute's value in Java, I can get the value properly but I couldn't modify the 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
}
}
}
最好的方法是什么?
推荐答案
JsonNode
是不可变的,用于解析操作。但是,它可以转换为允许突变的 ObjectNode
(和 ArrayNode
):
JsonNode
is immutable and is intended for parse operation. However, it can be cast into ObjectNode
(and ArrayNode
) that allow mutations:
((ObjectNode)jsonNode).put("value", "NO");
对于数组,您可以使用:
For an array, you can use:
((ObjectNode)jsonNode).putArray("arrayName").add(object.getValue());
这篇关于如何在Java中修改JsonNode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文