0

Is there something like

jsonNode.put("/deep/path/to/var", "myval")

or something with ObjectNode?

I know there are ways to iterate over the jsonNode and put something inside but my Question is. How could I use "/deep/path/to/..." as String to modify a value in a JSOn or also inside a map or something similar?

For example what I have is

{"deep":{
 "path": {
  "to":"value" 
  }
}

And now I want to change it to

{"deep":{
 "path": {
  "to":"otherValue" 
  }
}

My wish is that I just write a path to the key and change the value without iterating through the tree.

What I don't like to do is:

myMap.get("deep").get("path").put("to","otherValue");

What I like is something fancy like:

mySuperfancyObject.put("deep/path/to", "otherValue");

Is this possible?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Julian
  • 334
  • 4
  • 18
  • According to the documentation it seems you can use [`at()`](https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/JsonNode.html#at(java.lang.String)); – Mark Baijens Jun 16 '23 at 07:48
  • Does this answer your question? [How to modify JsonNode in Java?](https://stackoverflow.com/questions/30997362/how-to-modify-jsonnode-in-java) – Mar-Z Jun 16 '23 at 08:23
  • I do not understand how at(...) could help me – Julian Jun 16 '23 at 11:00

1 Answers1

0

Ah ok now I understand how to do it with

jsonNode.at("/deep/path");

This function returns a JsonNode and you could manipulate it when you cast it to an ObjectNode. If you do that the whole tree get this update.

So my code looks like:

JsonNode jsonNode = new ObjectMapper().valueToTree(myMap);
JsonNode nodeToSetValue = jsonNode.at("/deep/path");
String oldValue = ((ObjectNode) nodeToSetValue).get("finalKey").asText();
String newValue = changeValue(oldValue);
((ObjectNode) nodeToSetValue).put("finalKey", newValue);
myMap = new ObjectMapper().convertValue(jsonNode, new TypeReference<Map<String, Object>>(){}));
Julian
  • 334
  • 4
  • 18