如何在 Java 中修改 JsonNode?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30997362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:29:56  来源:igfitidea点击:

How to modify JsonNode in Java?

javajsonHymanson

提问by mstfdz

I need to change a JSON attribute's value in Java, I can get the value properly but I couldn't modify the JSON.

我需要在 Java 中更改 JSON 属性的值,我可以正确获取该值,但无法修改 JSON。

here is the code below

这是下面的代码

  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
            }
        }
    }

What is the best way to do this?

做这个的最好方式是什么?

采纳答案by Sharon Ben Asher

JsonNodeis immutable and is intended for parse operation. However, it can be cast into ObjectNode(and ArrayNode) that allow mutations:

JsonNode是不可变的,用于解析操作。但是,它可以被转换为允许突变的ObjectNode(and ArrayNode):

((ObjectNode)jsonNode).put("value", "NO");

For an array, you can use:

对于数组,您可以使用:

((ObjectNode)jsonNode).putArray("arrayName").add(object.ge??tValue());

回答by Eugen Halca

You need to get ObjectNodetype object in order to set values. Take a look at this

您需要获取ObjectNode类型对象才能设置值。看看这个

回答by Xdsasdf

I think you can just cast to ObjectNode and use putmethod. Like this

我认为你可以转换为 ObjectNode 并使用put方法。像这样

ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");

ObjectNode o = (ObjectNode) jsonNode; o.put("value", "NO");

回答by Mubashar

Just for the sake of understanding of others who may not get the whole picture clear following code works for me to find a field and then update it

只是为了理解其他人可能无法清楚地了解整个画面,以下代码对我有用,可以找到一个字段然后更新它

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(JsonString);    
JsonPointer valueNodePointer = JsonPointer.compile("/GrandObj/Obj/field");
JsonPointer containerPointer = valueNodePointer.head();
JsonNode parentJsonNode = rootNode.at(containerPointer);

if (!parentJsonNode.isMissingNode() && parentJsonNode.isObject()) {
    ObjectNode parentObjectNode = (ObjectNode) parentJsonNode;
    //following will give you just the field name. 
    //e.g. if pointer is /grandObject/Object/field
    //JsonPoint.last() will give you /field 
    //remember to take out the / character 
    String fieldName = valueNodePointer.last().toString();
    fieldName = fieldName.replace(Character.toString(JsonPointer.SEPARATOR), StringUtils.EMPTY);
    JsonNode fieldValueNode = parentObjectNode.get(fieldName);

    if(fieldValueNode != null) {
        parentObjectNode.put(fieldName, "NewValue");
    }
}

回答by Alejandro

The @Sharon-Ben-Asher answer is ok.

@Sharon-Ben-Asher 的回答没问题。

But in my case, for an array i have to use:

但就我而言,对于数组,我必须使用:

((ArrayNode) jsonNode).add("value");

回答by matrixanomaly

Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):

添加一个答案,因为其他一些人在已接受的答案的评论中表示赞同,他们在尝试转换为 ObjectNode(包括我自己)时遇到此异常:

Exception in thread "main" java.lang.ClassCastException: 
com.fasterxml.Hymanson.databind.node.TextNode cannot be cast to com.fasterxml.Hymanson.databind.node.ObjectNode

The solution is to get the 'parent' node, and perform a put, effectively replacing the entire node, regardless of original node type.

解决方案是获取“父”节点,并执行put,有效地替换整个节点,无论原始节点类型如何。

If you need to "modify" the node using the existing value of the node:

如果您需要使用节点的现有值“修改”节点:

  1. getthe value/array of the JsonNode
  2. Perform your modification on that value/array
  3. Proceed to call puton the parent.
  1. get的值/数组 JsonNode
  2. 对该值/数组执行修改
  3. 继续打电话put给父母。

Code, where the goal is to modify subfield, which is the child node of NodeAand Node1:

代码,其中的目标是修改和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");

Credits:

学分:

I got this inspiration from here, thanks to wassgreen@

感谢wassgreen@,我从这里得到了这个灵感