0

我试图通过以下代码中的更新向 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"}]}
4

1 回答 1

1

你正在改变同一个对象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());
于 2021-09-11T03:35:49.120 回答