在Java中动态修改未知JSON的JsonNode [英] Modify JsonNode of unknown JSON dynamically in Java
问题描述
我正在尝试修改一个JSON(未知结构),其中JsonPath及其等效的XML Xpath是我所知道的。
I am trying to modify a JSON (of an unknown structure) where the JsonPath and its equivalent XML Xpath is known to me.
我已经厌倦了使用 com.jayway.jsonpath.JsonPath
同样的库。
JsonPath的问题是,它返回值但我无法修改目标节点。
I have tired using com.jayway.jsonpath.JsonPath
library for the same.
The problem with JsonPath is, it returns me the value but I am not able to modify the Target Node.
以下是我的相同代码片段
Follows is my code snippet for the same
JsonPath.read(jsonFile, jsonPath);
JsonPath.parse(jsonPath);
System.out.println("Author: "+JsonPath.read(jsonFile, jsonPath));
我尝试使用Jackson,如以前要求的排队,但它需要逐个节点遍历,如下所示
I tried using Jackson as mentioned in previously asked quetion, But it needs to be traversed node by node as follows
((ObjectNode) parent).put(fieldName, newValue);
由于结构未知,我无法做到。
which I cannot do due to unknown structure.
我已经尝试过给出问题的答案以递归方式解析JSON对象但它说如何解析不修改
I have tried the answer given to the question recursively parse JSON object but it says how to parse not modify
我需要执行以下操作
JsonNode root = mapper.readTree("Json in form of String");
((JsonNode)(root.get("JsonPath")).set("New Value");
有什么方法可以实现这个目标吗?
Is there any way in which this can be achieved?
推荐答案
JsonNode
对象是不可变的,所以你不能修改它们。你可以做的是用另一个替换 JsonNode
。强制转换为 ObjectNode
也需要公开所需的方法。首先找到要替换的节点的父节点:
JsonNode
objects are immutable so you can't modify them. What you can do is replace a JsonNode
with another one. A cast to ObjectNode
is also required to expose the required methods. First find the parent of the node you want to replace :
JsonNode node = root.findParent("JsonPath");
然后使用其中任何一个用新方法替换它的2种方法:
Then use either of these 2 methods to replace it with a new one:
((ObjectNode) node).remove("JsonPath"); // remove current node
((ObjectNode) node).put("JsonPath", "New Value"); // add new one with new value
或
((ObjectNode) node).replace("JsonPath", new TextNode("New Value"));
这篇关于在Java中动态修改未知JSON的JsonNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!