Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change element value in ArrayNode

Tags:

java

json

jackson

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"?

like image 829
lg.lindstrom Avatar asked Jul 23 '15 08:07

lg.lindstrom


1 Answers

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"));
like image 96
Ernest Sadykov Avatar answered Sep 20 '22 03:09

Ernest Sadykov