lg.lindstrom
lg.lindstrom

Reputation: 856

How to change element value in ArrayNode

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

Upvotes: 6

Views: 10036

Answers (1)

Ernest Sadykov
Ernest Sadykov

Reputation: 831

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

Upvotes: 7

Related Questions