javajackson-databindjsonnode

Adding new items to ArrayNode with updates in JsonNode


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"}]}

Solution

  • 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());