I have a following test code:
Model model = new Model();
model.setName("Alex");
model.setAddress("NY");
Map<Object, Object> attrs = new HashMap<>();
attrs.put("address", "London");
I need to patch my existing model object with only values from attrs Map.
so, after the executing the code I need to have existing model object with a following values:
name: Alex
address: London
Is it possible to implement with Jackson library ? If so, please show an example.
It definitely can be achieved with Jackson. As mentioned by yshavit, the following will do the trick:
ObjectMapper mapper = new ObjectMapper();
// Convert POJO to Map
Map<String, Object> modelAsMap =
mapper.convertValue(model, new TypeReference<Map<String, Object>>() {});
// Merge maps
modelAsMap.putAll(attrs);
// Convert Map to POJO
Model modelPatched = mapper.convertValue(modelAsMap, Model.class);
For more details on mapping a POJO to a Map and vice versa, refer to this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With