Search code examples
javajsonspringjson-patch

Get/Modify specific data from jsonPatch request


I need to modify JSONPatch before applying it to the main object, I search a lot but didn't find any solution.

I have a JSONPatch request something like this:

[op: replace; path: "/size"; value: "1", op: replace; path: "/name"; value: "test"]

Now in the below code, I want a loop for this JSONPatch object to modify some values (for example name).

public void patch(JsonPatch jsonPatch) throws JsonPatchException {
   
   // need a foreach here to access JSONPatch object to modify some values

   jsonPatch.apply(objectMapper.convertValue(myObject, JsonNode.class));
   
}

Solution

  • Found a solution by doing something like this:

    var jsonPatchList = objectMapper.convertValue(jsonPatch, JsonNode.class);
    
    for(int i = 0; i < jsonPatchList.size(); i++) {
        log.debug("Path: {}", jsonPatchList.get(i).get("path"));
        log.debug("Value: {}", jsonPatchList.get(i).get("value"));
    }