Shabar
Shabar

Reputation: 2823

Edit object in nested array in json object with JsonNode

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"
}

Upvotes: 1

Views: 2996

Answers (2)

ZINE Mahmoud
ZINE Mahmoud

Reputation: 1332

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

Upvotes: 2

adq
adq

Reputation: 184

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

Upvotes: 2

Related Questions