使用 JsonNode 编辑 json 对象中嵌套数组中的对象

Edit object in nested array in json object with JsonNode

我试图将嵌套数组项 "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"
}

首先访问包装数组,然后修改第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);

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