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

Record class support for ObjectMapper#updateValue

Open dodie opened this issue 4 years ago • 10 comments

updateValue is a convenient way to update the fields of a POJO and it even supports changing hierarchical values.

Currently when the object to be updated is an instance of a Record class it throws an exception, rightfully because the fields of the record are immutable:

record Person(String name, Integer age);
Person original = new Person("John", 15);
new ObjectMapper().updateValue(originalRecord, Map.of("name", "Jane"));
// ↑ JsonMappingException: Can not set final java.lang.String field a.b.c.Person.name to java.lang.String 

Would it be feasible for the updateValue to support Record classes in such a way that it would not update the object in place, but instead it would return a new object with the updated values?

For example:

record Person(String name, Integer age);
Person original = new Person("John", 25);
Person updated = new ObjectMapper().updateValue(originalRecord, Map.of("name", "Jane"));

// the values of `original` would remain unchanged
// Person[name="John", age=25]

// the data of the `updated` record would be based on the `original` record and the updates
// Person[name="Jane", age=25] 

Based on its signature this behavior is already in place for arrays.

dodie avatar Mar 14 '21 09:03 dodie