I'm trying to get my head around the convertValue
method of Jackson. Initially I thought it would be somewhat equivalent to the Gson#fromJson
method but this doesn't seem to be the case.
Here's the problem:
// Map<String, Object> map = ...
ObjectMapper mapper = new ObjectMapper();
MyPojo pojo = mapper.convertValue(map.get(key), MyPojo.class);
for (Map.Entry<String, Object> m : map.entrySet()) {
System.out.println("k=" + m.getKey() + " v=" + m.getValue());
}
pojo.name = "Banana";
for (Map.Entry<String, Object> m : map.entrySet()) {
System.out.println("k=" + m.getKey() + " v=" + m.getValue());
}
Output
k=66e8c013 v=MyPojo{name='Apple'}
k=66e8c013 v=MyPojo{name='Banana'}
Note: Code and output has been stripped down to the relevant part
So, if I modify my pojo object, it's also getting changed in the original Map
. For me it seems like Jackson doesn't call "new MyPojo()" internally and set the values for each found variable afterwards.
What can I do to prevent this? Is there an alternative method? Do I need to create a copy constructor in order to get a truly new object without references to the values in the Map?
Additionally it would be cool if someone could tell me what convertValue
actually does.