Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson patch object by map

Tags:

java

jackson

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.

like image 209
alexanoid Avatar asked Feb 19 '26 01:02

alexanoid


1 Answers

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.

like image 59
cassiomolin Avatar answered Feb 21 '26 16:02

cassiomolin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!