Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

jackson - Modify JsonNode of unknown JSON dynamically in Java

I am trying to modify a JSON (of an unknown structure) where the JsonPath and its equivalent XML Xpath is known to me.

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

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.

I have tried the answer given to the question recursively parse JSON object but it says how to parse not modify

I need to do the follows

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

or

((ObjectNode) node).replace("JsonPath", new TextNode("New Value"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...