简体   繁体   English

如何修改Java中的JsonNode?

[英]How to modify JsonNode in Java?

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?做这个的最好方式是什么?

JsonNode is immutable and is intended for parse operation. JsonNode是不可变的,用于解析操作。 However, it can be cast into ObjectNode (and ArrayNode ) that allow mutations: 但是,它可以转换为允许突变的ObjectNode (和ArrayNode ):

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

For an array, you can use: 对于数组,您可以使用:

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

I think you can just cast to ObjectNode and use put method. 我想你可以转换为ObjectNode并使用put方法。 Like this 像这样

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

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");

You need to get ObjectNode type object in order to set values. 您需要获取ObjectNode类型对象才能设置值。 Take a look at this 看看这个

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.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.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. get the value/array of the JsonNode get JsonNode的值/数组
  2. Perform your modification on that value/array 对该值/数组执行修改
  3. Proceed to call put on the parent. 继续打电话put父母。

Code, where the goal is to modify subfield , which is the child node of NodeA and 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 @

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nodeMap = mapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>(){});
nodeMap.put("key", "value");
jsonNode = mapper.convertValue(nodeMap, JsonNode.class);

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM