I have this file (example.json):
{
"messages" : [ "msg 1", "msg 2", "msg 3" ],
}
Then I create a JsonNode
like this:
BufferedReader fileReader = new BufferedReader(new FileReader("example.json"));
JsonNode rootNode = mapper.readTree(fileReader);
How do I change the array element value from "msg 1" to "msg 1A" without removing the element and adding a new one with value "msg 1A"?
If you want to change first element of the messages
array, use following code:
((ArrayNode) rootNode.withArray("messages")).set(0, new TextNode("msg 1A"));
UPD
Another version, which removes and then inserts element (that is what you try to avoid):
((ArrayNode) rootNode.withArray("messages")).remove(0);
((ArrayNode) rootNode.withArray("messages")).insert(0, new TextNode("msg 1A"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With