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"
}
2
  • 1
    You are editing in root node get item3 node and it's first object and edit root.get("item3").get(0) Commented Aug 8, 2020 at 11:16
  • This works ((ObjectNode) root.get("item3").get(0)).put("field2", "xxxx"); Commented Aug 9, 2020 at 0:05

2 Answers 2

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"}]}
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Can we use ((ObjectNode)root).putArray("item3")....here?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.