jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

ObjectNode - Provide `put(JsonPointer ptr, JsonNode node)` and `put(JsonPointer ptr, {primitiveDataType} value)` methods

Open SaiKrishna369 opened this issue 2 years ago • 3 comments

There is no mechanism to edit/create a value in the json tree without first navigating to the parent node and then using set or replace or put methods. Starting from version 2.14, within an ObjectNode using withObject and withArray methods, new nodes can be created on a non-existent path. These two methods can further be extended to enhance put method, providing a feature to directly create and set value along a path or modify an existing path.

Describe the solution you'd like put(JsonPointer ptr, JsonNode node) or put(JsonPointer ptr, {primitiveDataType} value) would create the path if it doesn't exist, then auto navigates to the node atptr.head() and sets the provided value at the key ptr.last().

Usage example

@Test
public static void test_nestedArray() {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonObject
        String json = "{}";
        try {
            jsonObject = mapper.readTree(json);
            jsonObject.put("/key1/array1/0/element1", 1);
            jsonObject.put("/key1/array1/0/element2", 2);
            jsonObject.put("/key1/array1/1/element1", 3);
            jsonObject.put("/key1/array1/1/element2", 4);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        assertEquals(jsonObject.toString(), {"key1": { "array1": [ {"element1": 1, "element2": 2}, {"element1": 3, "element2": 4} ] } });
    }

Additional context [Filtering Json] Right now, there is no straight forward way to copy selected paths from one json to another. This feature would simplify this task.

SaiKrishna369 avatar Apr 15 '23 20:04 SaiKrishna369