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