使用 JsonNode 中的更新将新项目添加到 ArrayNode

Adding new items to ArrayNode with updates in JsonNode

我试图通过以下代码中的更新向 JsonNode 添加新的数组项。

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

预期结果:

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

但我低于

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

您正在改变同一个对象 JsonNode arrayObject = inputArrayNode.get(0);,要解决这个问题,您可以创建一个新的局部变量 JsonNode

此代码适合您

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