6

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

1 Answer 1

7

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"));
Sign up to request clarification or add additional context in comments.

5 Comments

Yes,, can do that. But that is actually what I not did want to do,, remove the element,, and add a new.
@lg.lindstrom actually, that is exactly what you want: my code changes the element. You can check that using source code of ArrayNode (which is backed up by ArrayList).
uhhh,, I see the difference. I try it out.
@lg.lindstrom I understood what you meant. You cannot change the message itself in-place, because every array element is a TextNode, which is immutable.
okey. I understand. This is not what I hoped for,, but a answer smile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.