1

我试图将嵌套数组项中的对象编辑 "field2": "desc 2""field2": "xxxx"下面的 json 中:

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

我试过这个解决方案

root = objectMapper.readTree(new File(filePath))
((ObjectNode) root).put("field2", "desc xxxx");

输出是:

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

2 回答 2

2

先访问被包装的数组,然后修改第 0 个元素:

JsonNode root = objectMapper.readTree(new File(filePath));
ObjectNode item3element0 = (ObjectNode) root.get("item3").get(0);
item3element0.put("field2", "desc xxxx");

...或构造一个ArrayNode,向其中添加元素,然后将其添加到根:

JsonNode root = objectMapper.readTree(new File(filePath));
ArrayNode newArr = objectMapper.createArrayNode();
ObjectNode field2Element = objectMapper.createObjectNode();
field2Element.put("field2", "desc xxxx");
newArr.add(field2Element);
root.set("item3", newArr);
于 2020-08-08T11:03:16.167 回答
2

使用 ObjectMapper 和 JsonNode 更新 json(复杂的 json(json 数组和对象) *

解决方案 :

String json= "{\n" +
        "  \"item1\": 123,\n" +
        "  \"item2\": \"desc 1\",\n" +
        "  \"item3\": [{\"field1\": \"desc 1\", \"field2\": \"desc 2\"}]\n" +
        "}";
try {
    JsonNode node;
    ObjectMapper mapper = new ObjectMapper();
    node = mapper.readTree(json);
    node.get("item3").forEach(obj -> {
        ((ObjectNode)obj).put("field2", "xxxxxxxxxxxxxx");
    });
    System.out.println(node);
} catch (JsonMappingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (JsonProcessingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

结果:

{"item1":123,"item2":"desc 1","item3":[{"field1":"desc 1","field2":"xxxxxxxxxxxxxx"}]}
于 2020-08-08T11:12:00.983 回答