Mapper instances are fully thread-safe, there is no need to create a mapper for single use, but mapper's config can be changed.
Although ObjectMapper has copy function to duplicate the config for customize based on exists mapper, if I share a mapper, there is no guarantee that when someone want to customize the mapper, they will copy the shared mapper. So I want a immutable mapper to share, if someone accidently changed the shared mapper, some exception should be throw.
Is there something like this ?
Jackson's ObjectMapper is completely thread safe and should not be re-instantiated every time #2170.
Yes, that is safe and recommended.
Note that copy() operation is as expensive as constructing a new ObjectMapper instance: if possible, you should still pool and reuse mappers if you intend to use them for multiple operations.
Data classes has a restriction to have at-least one primary constructor parameter so no default/no-args constructor is available by default in data classes. Jackson is unable to find the default constructor so it's unable to create an object of Person class and throwing the InvalidDefinitionException exception.
One approach is to not share the ObjectMapper
instance, but rather configure it correctly and then share instances of ObjectWriter
and ObjectReader
created by the ObjectMapper
.
ObjectMapper om = new ObjectMapper();
// Configure to your needs
om.enable(...);
om.disable(...);
// Distribute these to the parts of the program where you fear configuration changes.
ObjectWriter writer = om.writer();
ObjectReader reader = om.reader();
This also seems to be the approach favoured by the developers of Jackson: https://stackoverflow.com/a/3909846/13075
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