1

I was trying to edit object in nested array item "field2": "desc 2" to "field2": "xxxx" in below json:

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

I tried this solution

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

Output was:

{
  "item1": 123,
  "item2": "desc 1",
  "item3": [
    {
      "field1": "desc 1",
      "field2": "desc 2"
    }
  ],
  "field2": "desc xxxx"
}
ZINE Mahmoud
  • 1,272
  • 1
  • 17
  • 32
Shabar
  • 2,617
  • 11
  • 57
  • 98

2 Answers2

2

Access the wrapped array first, then modify the 0th element:

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

...or construct an ArrayNode, add elements to it, and add that to the root:

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);
adq
  • 184
  • 7
  • Can we use ((ObjectNode)root).putArray("item3")....here? – Shabar Aug 08 '20 at 11:09
  • Sure, that would work if you want to put an empty `ArrayNode` in and add through it. Alternatively, you can construct an `ArrayNode` from scratch and modify it that way. There's probably some other ways of doing it as well. – adq Aug 08 '20 at 11:11
2

Update json with ObjectMapper and JsonNode (complex json (json arrays and objects ) *

solution :

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

result:

{"item1":123,"item2":"desc 1","item3":[{"field1":"desc 1","field2":"xxxxxxxxxxxxxx"}]}
ZINE Mahmoud
  • 1,272
  • 1
  • 17
  • 32