Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Jackson, How to safely share an ObjectMapper ? Is there any immutable ObjectMapper?

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 ?

like image 694
wener Avatar asked Apr 26 '17 07:04

wener


People also ask

Is ObjectMapper thread-safe Jackson?

Jackson's ObjectMapper is completely thread safe and should not be re-instantiated every time #2170.

Should Jackson ObjectMapper be static?

Yes, that is safe and recommended.

Can ObjectMapper be reused?

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.

Why does Jackson need a default constructor?

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.


1 Answers

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

like image 193
Henrik Aasted Sørensen Avatar answered Sep 28 '22 06:09

Henrik Aasted Sørensen