How to remove unwanted json (sub)node from root node

1.9k views Asked by At

Here is my json request:

{
 {"op":"replace", "path":"/news", "value":"A"},
 {"op":"replace", "path":"/videos", "value":"B"},
 {"op":"replace", "path":"/photos", "value":"C"}
}

In my controller:

JsonNode jsonNode = null;
    try {
          //patchJson is json string (above)
        jsonNode = new ObjectMapper().readTree(patchJson);
        for (JsonNode node : jsonNode) {
            String path = node.path("path").asText();
            if(path.equalsIgnoreCase("/photos"))
            {
              //How to remove this node from root node(jsonNode)
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    Patch patch = new JsonPatchMaker().fromJsonNode(jsonNode);

Can someone please help me how to remove the node with "photos" in path?

1

There are 1 answers

2
kleash On

There are lot of ways to remove it.

One is you can store index of nodes with "photos" in path and than iterate over all index and call remove function which I mentioned below.


OR maintain one more copy of jsonnode and remove elements from that copy while iterating over original copy. So it would look something like this:-

JsonNode jsonNode = null;
    try {
          //patchJson is json string (above)
        jsonNode = new ObjectMapper().readTree(patchJson);
        *JsonNode jsonNode2 = jsonNode.deepCopy();*
        *int index = 0;*
        *int changedCount = 0;*
        for (JsonNode node : jsonNode) {
            String path = node.path("path").asText();
            if(path.equalsIgnoreCase("/photos"))
            {
              *((ArrayNode) jsonNode2).remove(index-changedCount);*
              *changedCount++;*
            }
            *index++;*
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

Also your JSON is an array so it should be starting with [] not {}.