0

I was trying to add new array items to the JsonNode with updates in below code.

String request = "{\n" +
            "  \"item1\": 123,\n" +
            "  \"item2\": \"desc 1\",\n" +
            "  \"item3\": [{\"field1\": \"desc 1\", \"field2\": \"desc 2\"}]\n" +
            "}";

            JsonNode node = mapper.readTree(request);

            ArrayNode inputArrayNode = (ArrayNode) node.findValue("item3");
            JsonNode arrayObject = inputArrayNode.get(0);

            for (int i = 0; i < 3; i++) {
                
                ((ObjectNode) arrayObject).put("field1", "xxxxxxxxx" + i);
                inputArrayNode.add(arrayObject);
                ((ObjectNode) node).putArray("item3").addAll(inputArrayNode);
            }

Expected Result:

{"item1":123,
 "item2":"desc 1",
   "item3":[{"field1":"xxxxxxxxx0","field2":"desc 2"},
            {"field1":"xxxxxxxxx1","field2":"desc 2"},
            {"field1":"xxxxxxxxx2","field2":"desc 2"}]}

But I get below

{"item1":123,
     "item2":"desc 1",
       "item3":[{"field1":"xxxxxxxxx2","field2":"desc 2"},
                {"field1":"xxxxxxxxx2","field2":"desc 2"},
                {"field1":"xxxxxxxxx2","field2":"desc 2"}]}

1 Answer 1

1

You're mutating the same object JsonNode arrayObject = inputArrayNode.get(0);, to fix that, you can create a new local variable JsonNode.

This code will work for you

ArrayNode inputArrayNode = (ArrayNode) node.findValue("item3");
JsonNode arrayObjectOrigin = inputArrayNode.get(0);
for (int i = 0; i < 3; i++) {
    JsonNode arrayObject = arrayObjectOrigin.deepCopy();
    ((ObjectNode) arrayObject).put("field1", "xxxxxxxxx" + i);
    inputArrayNode.add(arrayObject);
}
inputArrayNode.remove(0);

System.out.println(node.toPrettyString());
Sign up to request clarification or add additional context in comments.

1 Comment

Great that works, So ((ObjectNode) node).putArray("item3").addAll(inputArrayNode); doesn't help here.

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.